Back to index

gcompris  8.2.2
pythontest.py
Go to the documentation of this file.
00001 # PythonTest Board module
00002 import gnomecanvas
00003 import gcompris
00004 import gcompris.utils
00005 import gcompris.skin
00006 import gcompris.admin
00007 import gtk
00008 import gtk.gdk
00009 import random
00010 
00011 from gcompris import gcompris_gettext as _
00012 
00013 class Gcompris_pythontest:
00014   """Testing gcompris python class"""
00015 
00016 
00017   def __init__(self, gcomprisBoard):
00018     self.gcomprisBoard = gcomprisBoard
00019 
00020     self.gcomprisBoard.disable_im_context = True
00021 
00022     self.canvasitems = {}
00023 
00024     self.colors = {}
00025     self.colors['circle_in'] = gcompris.skin.get_color("pythontest/circle in")
00026     self.colors['circle_out'] = gcompris.skin.get_color("pythontest/circle out")
00027     self.colors['line'] = gcompris.skin.get_color("pythontest/line")
00028 
00029     # Just for config demo
00030     self.config_colors = { 'red' : 0xFF0000FFL,
00031                            'green' : 0x00FF00FFL,
00032                            'blue' : 0x0000FFFFL }
00033 
00034     # dict .keys() list of keys has random order
00035     self.config_colors_list = [ 'red', 'green', 'blue']
00036 
00037     self.movingline='none'
00038 
00039     # Find a number game
00040     self.solution = random.randint(0,9)
00041 
00042     print("Gcompris_pythontest __init__.")
00043 
00044     #initialisation to default values. Some of them will be replaced by
00045     #the configured values.
00046 
00047   def start(self):
00048     logged = gcompris.admin.get_current_user()
00049 
00050     wordlist = gcompris.get_wordlist('wordslevel_max_pt_BR')
00051     print wordlist
00052 #    print wordlist.filename
00053 #    print wordlist.level
00054 #    print wordlist.locale
00055 #    print wordlist.description
00056 #    print wordlist.words
00057 
00058 
00059     print gcompris.get_current_user_dirname()
00060     print gcompris.get_current_board_dirname()
00061 
00062     if logged:
00063       print "User Logged in:"
00064       print "   ", logged.login, logged.firstname, logged.lastname
00065 
00066     self.gcomprisBoard.level=1
00067     self.gcomprisBoard.maxlevel=1
00068     self.gcomprisBoard.sublevel=1
00069     self.gcomprisBoard.number_of_sublevel=1
00070 
00071     # init config to default values
00072     self.config_dict = self.init_config()
00073 
00074     print "init self.config_dict :", self.config_dict
00075 
00076     # change configured values
00077     print "gcompris.get_board_conf() : ", gcompris.get_board_conf()
00078     self.config_dict.update(gcompris.get_board_conf())
00079 
00080     print "self.config_dict final :", self.config_dict
00081 
00082     self.previous_locale = gcompris.get_locale()
00083 
00084     if self.config_dict.has_key('locale'):
00085       gcompris.change_locale(self.config_dict['locale'])
00086 
00087     # self.colors['line'] s set in init.
00088     # I put here the configuration use
00089 
00090     color_name = self.config_dict['color_line']
00091     self.colors['line'] = self.config_colors[color_name]
00092 
00093     gcompris.bar_set(gcompris.BAR_CONFIG)
00094     gcompris.set_background(self.gcomprisBoard.canvas.root(),
00095                             gcompris.skin.image_to_skin("gcompris-bg.jpg"))
00096     gcompris.bar_set_level(self.gcomprisBoard)
00097 
00098     # Create our rootitem. We put each canvas item in it so at the end we
00099     # only have to kill it. The canvas deletes all the items it contains automaticaly.
00100     self.rootitem = self.gcomprisBoard.canvas.root().add(
00101       gnomecanvas.CanvasGroup,
00102       x=0.0,
00103       y=0.0
00104       )
00105 
00106     # distance is used to demo of gcompris.spin_int
00107     distance = eval(self.config_dict['distance_circle'])
00108 
00109     # pattern is for gcompris.radio_buttons
00110     pattern = self.config_dict['pattern']
00111 
00112     patterns = { 'circle': gnomecanvas.CanvasEllipse,
00113                  'rectangle': gnomecanvas.CanvasRect
00114                  }
00115 
00116     #error check
00117     if not patterns.has_key(pattern):
00118       pattern = 'circle'
00119 
00120     self.canvasitems[1] = self.rootitem.add(
00121       patterns[pattern],
00122       x1=400.0 - distance ,
00123       y1=200.0,
00124       x2=380.0 - distance,
00125       y2=220.0,
00126       fill_color_rgba= self.colors['circle_in'],
00127       outline_color_rgba= self.colors['circle_out'],
00128       width_units=1.0
00129       )
00130     self.canvasitems[1].connect("event", self.circle_item_event)
00131 
00132     self.canvasitems[2] = self.rootitem.add(
00133       patterns[pattern],
00134       x1=400.0 + distance,
00135       y1=200.0,
00136       x2=420.0 + distance,
00137       y2=220.0,
00138       fill_color_rgba= self.colors['circle_in'],
00139       outline_color_rgba= self.colors['circle_out'],
00140       width_units=1.0
00141       )
00142     self.canvasitems[2].connect("event", self.circle_item_event)
00143 
00144     self.canvasitems[3] = self.rootitem.add(
00145       gnomecanvas.CanvasText,
00146       x=400.0,
00147       y=100.0,
00148       text=_("This is the first plugin in gcompris coded in the Python\nProgramming language."),
00149       fill_color="white",
00150       justification=gtk.JUSTIFY_CENTER
00151       )
00152 
00153     self.canvasitems[4] = self.rootitem.add(
00154       gnomecanvas.CanvasText,
00155       x=400.0,
00156       y=140.0,
00157       text=_("It is now possible to develop gcompris activities in C or in Python.\nThanks to Olivier Samys who makes this possible."),
00158       fill_color="white",
00159       justification=gtk.JUSTIFY_CENTER
00160       )
00161 
00162     self.canvasitems[5] = self.rootitem.add(
00163       gnomecanvas.CanvasText,
00164       x=400.0,
00165       y=250.0,
00166       text=_("This activity is not playable, just a test"),
00167       fill_color="white",
00168       justification=gtk.JUSTIFY_CENTER
00169       )
00170 
00171     #----------------------------------------
00172     # A simple game.
00173     # Try to hit left shift and right shift together. The peed increases
00174     self.rootitem.add(
00175           gnomecanvas.CanvasRect,
00176           x1=20,
00177           y1=gcompris.BOARD_HEIGHT-180,
00178           x2=gcompris.BOARD_WIDTH-20,
00179           y2=gcompris.BOARD_HEIGHT-10,
00180           fill_color_rgba=0x101077FFL,
00181           outline_color_rgba=0x07A3E080L,
00182           width_units=2.0)
00183 
00184     # For the game status WIN/LOOSE
00185     self.canvasitems[6] = self.rootitem.add(
00186       gnomecanvas.CanvasText,
00187       x=gcompris.BOARD_WIDTH / 2,
00188       y=gcompris.BOARD_HEIGHT - 40,
00189       font=gcompris.skin.get_font("gcompris/content"),
00190       fill_color_rgba=0x123456FFL,
00191       justification=gtk.JUSTIFY_CENTER
00192       )
00193 
00194     self.rootitem.add(
00195       gnomecanvas.CanvasText,
00196       x=400.0,
00197       y=400.0,
00198       text=("Test your reflex with the counter. Hit the 2 shifts key together.\nHit space to reset the counter and increase the speed.\nBackspace to reset the speed"),
00199       fill_color="white",
00200       justification=gtk.JUSTIFY_CENTER
00201       )
00202 
00203     # The basic tick for object moves
00204     self.timerinc = 1000
00205 
00206     self.timer_inc  = gtk.timeout_add(self.timerinc, self.timer_inc_display)
00207 
00208     self.counter_left  = 0
00209     self.counter_right = 0
00210 
00211     self.canvasitems[7] = self.rootitem.add(
00212       gnomecanvas.CanvasText,
00213       x=gcompris.BOARD_WIDTH / 2,
00214       y=gcompris.BOARD_HEIGHT - 80,
00215       font=gcompris.skin.get_font("gcompris/content"),
00216       text="Speed="+str(self.timerinc)+" ms",
00217       fill_color="white",
00218       justification=gtk.JUSTIFY_CENTER
00219       )
00220 
00221     self.textitem_left = self.rootitem.add(
00222       gnomecanvas.CanvasText,
00223       font=gcompris.skin.get_font("gcompris/content"),
00224       x=gcompris.BOARD_WIDTH / 3,
00225       y=gcompris.BOARD_HEIGHT - 40,
00226       fill_color_rgba=0xFFFFFFFFL
00227       )
00228 
00229     self.textitem_right = self.rootitem.add(
00230       gnomecanvas.CanvasText,
00231       font=gcompris.skin.get_font("gcompris/content"),
00232       x=gcompris.BOARD_WIDTH / 1.5,
00233       y=gcompris.BOARD_HEIGHT - 40,
00234       fill_color_rgba=0xFFFFFFFFL
00235       )
00236 
00237     self.left_continue  = True
00238     self.right_continue = True
00239 
00240     print("Gcompris_pythontest start.")
00241 
00242 
00243   def end(self):
00244 
00245     gcompris.reset_locale()
00246 
00247     # Remove the root item removes all the others inside it
00248     self.rootitem.destroy()
00249 
00250     if self.timer_inc :
00251       gtk.timeout_remove(self.timer_inc)
00252 
00253 
00254   def ok(self):
00255     print("Gcompris_pythontest ok.")
00256 
00257 
00258   def repeat(self):
00259     print("Gcompris_pythontest repeat.")
00260 
00261 
00262   def config(self):
00263     print("Gcompris_pythontest config.")
00264 
00265 
00266   def key_press(self, keyval, commit_str, preedit_str):
00267     print("Gcompris_pythontest key press. %i %s" % (keyval, str))
00268 
00269     utf8char = gtk.gdk.keyval_to_unicode(keyval)
00270     strn = u'%c' % utf8char
00271 
00272     win = False
00273 
00274     if (keyval == gtk.keysyms.Shift_L):
00275       self.left_continue  = False
00276 
00277     if (keyval == gtk.keysyms.Shift_R):
00278       self.right_continue = False
00279 
00280     if(not self.left_continue and not self.right_continue):
00281       if(self.counter_left == self.counter_right):
00282         self.canvasitems[6].set(text="WIN",
00283                                 fill_color_rgba=0x2bf9f2FFL)
00284         win=True
00285       else:
00286         self.canvasitems[6].set(text="LOOSE",
00287                                 fill_color_rgba=0xFF0000FFL)
00288 
00289     if ((keyval == gtk.keysyms.BackSpace) or
00290         (keyval == gtk.keysyms.Delete)):
00291       self.timerinc = 1100
00292       keyval = 32
00293 
00294     if (keyval == 32):
00295       self.left_continue  = True
00296       self.right_continue = True
00297       self.counter_left  = 0
00298       self.counter_right = 0
00299       if(win):
00300         if(self.timerinc>500):
00301           self.timerinc -= 100
00302         elif(self.timerinc>200):
00303           self.timerinc -= 50
00304         elif(self.timerinc>10):
00305           self.timerinc -= 10
00306         elif(self.timerinc>1):
00307           self.timerinc -= 1
00308 
00309       if(self.timerinc<1):
00310           self.timerinc = 1
00311 
00312       self.canvasitems[3].set(text="")
00313       self.canvasitems[6].set(text="")
00314 
00315     self.canvasitems[7].set(text="Speed="+str(self.timerinc)+" ms")
00316 
00317     # Find a number game
00318     if str(self.solution) == strn:
00319       print "WIN"
00320     else:
00321       print "LOST"
00322 
00323     # Return  True  if you did process a key
00324     # Return  False if you did not processed a key
00325     #         (gtk need to send it to next widget)
00326     return True
00327 
00328   def pause(self, pause):
00329     print("Gcompris_pythontest pause. %i" % pause)
00330 
00331 
00332   def set_level(self, level):
00333     print("Gcompris_pythontest set level. %i" % level)
00334 
00335 # ---- End of Initialisation
00336 
00337   def timer_inc_display(self):
00338 
00339     if(self.left_continue):
00340       self.textitem_left.set(text=str(self.counter_left))
00341       self.counter_left += self.timer_inc
00342 
00343     if(self.right_continue):
00344       self.textitem_right.set(text=str(self.counter_right))
00345       self.counter_right += self.timer_inc
00346 
00347     self.timer_inc  = gtk.timeout_add(self.timerinc, self.timer_inc_display)
00348 
00349   def circle_item_event(self, widget, event=None):
00350     if eval(self.config_dict['disable_line']):
00351       return False
00352 
00353     if event.type == gtk.gdk.BUTTON_PRESS:
00354       if event.button == 1:
00355         bounds = widget.get_bounds()
00356         self.pos_x = (bounds[0]+bounds[2])/2
00357         self.pos_y = (bounds[1]+bounds[3])/2
00358         if 'line 1' in self.canvasitems:
00359           self.canvasitems['line 1'].destroy()
00360         self.canvasitems['line 1'] = self.rootitem.add(
00361           gnomecanvas.CanvasLine,
00362           points=( self.pos_x, self.pos_y, event.x, event.y),
00363           fill_color_rgba=self.colors['line'],
00364           width_units=5.0
00365           )
00366         self.movingline='line 1'
00367         print "Button press"
00368         return True
00369     if event.type == gtk.gdk.MOTION_NOTIFY:
00370       if event.state & gtk.gdk.BUTTON1_MASK:
00371         self.canvasitems[self.movingline].set(
00372           points=( self.pos_x, self.pos_y, event.x, event.y)
00373           )
00374     if event.type == gtk.gdk.BUTTON_RELEASE:
00375       if event.button == 1:
00376         self.movingline='line 1'
00377         print "Button release"
00378         return True
00379     return False
00380 
00381   ###################################################
00382   # Configuration system
00383   ###################################################
00384 
00385   #mandatory but unused yet
00386   def config_stop(self):
00387     pass
00388 
00389   # Configuration function.
00390   def config_start(self, profile):
00391     # keep profile in mind
00392     # profile can be Py_None
00393     self.configuring_profile = profile
00394 
00395     # init with default values
00396     self.config_dict = self.init_config()
00397 
00398     #get the configured values for that profile
00399     self.config_dict.update(gcompris.get_conf(profile, self.gcomprisBoard))
00400 
00401     # Init configuration window:
00402     # all the configuration functions will use it
00403     # all the configuration functions returns values for their key in
00404     # the dict passed to the apply_callback
00405     # the returned value is the main GtkVBox of the window,
00406     #we can add what you want in it.
00407 
00408     self.main_vbox = gcompris.configuration_window ( \
00409       _('<b>%s</b> configuration\n for profile <b>%s</b>') % ('Pythontest', profile.name ),
00410       self.ok_callback
00411       )
00412 
00413     # toggle box
00414     control_line = gcompris.boolean_box(_('Disable line drawing in circle'),
00415                                         'disable_line',
00416                                         eval(self.config_dict['disable_line'])
00417                                         )
00418     # sample of control in python
00419     control_line.connect("toggled", self.color_disable)
00420 
00421     # combo box
00422     self.color_choice = \
00423        gcompris.combo_box(_('Color of the line'),
00424                           self.config_colors_list,
00425                           'color_line',
00426                           self.config_dict['color_line']
00427                           )
00428     self.color_choice.set_sensitive(not eval(self.config_dict['disable_line']))
00429 
00430     gcompris.separator()
00431 
00432     #spin button for int
00433     self.distance_box = \
00434        gcompris.spin_int(_('Distance between circles'),
00435                          'distance_circle',
00436                          20,
00437                          200,
00438                          20,
00439                          eval(self.config_dict['distance_circle'])
00440                          )
00441 
00442     gcompris.separator()
00443 
00444     #radio buttons for circle or rectangle
00445     patterns = { 'circle': _('Use circles'),
00446                  'rectangle': _('Use rectangles')
00447                  }
00448 
00449     gcompris.radio_buttons(_('Choice of pattern'),
00450                            'pattern',
00451                            patterns,
00452                            self.config_dict['pattern']
00453                            )
00454 
00455     print "List of locales shown in gcompris.combo_locale :"
00456     print gcompris.get_locales_list()
00457 
00458     gcompris.separator()
00459 
00460     gcompris.combo_locales( self.config_dict['locale'])
00461 
00462     gcompris.separator()
00463 
00464     print "List of locales shown in gcompris.combo_locales_asset :"
00465     locales_purple = gcompris.get_locales_asset_list( "gcompris colors", None, "audio/x-ogg", "purple.ogg")
00466     print locales_purple
00467 
00468     label = gtk.Label()
00469     label.set_markup('<i>-- unused, but here for test --</i>')
00470     label.show()
00471     self.main_vbox.pack_start (label, False, False, 8)
00472 
00473     gcompris.combo_locales_asset( _("Select sound locale"), self.config_dict['locale_sound'], "gcompris colors", None, "audio/x-ogg", "purple.ogg" )
00474 
00475     print gcompris.utils.get_asset_file ("gcompris colors", None, "audio/x-ogg", "purple.ogg")
00476     print gcompris.utils.get_asset_file_locale ("gcompris colors", None, "audio/x-ogg", "purple.ogg", None)
00477     for lang in locales_purple:
00478       print gcompris.utils.get_asset_file_locale ("gcompris colors", None, "audio/x-ogg", "purple.ogg", lang)
00479 
00480   def color_disable(self, button):
00481     self.color_choice.set_sensitive(not button.get_active())
00482 
00483   # Callback when the "OK" button is clicked in configuration window
00484   # this get all the _changed_ values
00485   def ok_callback(self, table):
00486     if (table == None):
00487       print 'Configuration returns None'
00488       return
00489 
00490     print "Keys and values returned by PythonTest config window:"
00491 
00492     if (len(table) == 0):
00493         print '%20s' % 'None'
00494 
00495     for key,value in table.iteritems():
00496       print '%20s:%20s    ' % (key, value)
00497       gcompris.set_board_conf(self.configuring_profile, self.gcomprisBoard, key, value)
00498 
00499 
00500   def init_config(self):
00501     default_config = { 'disable_line'    : 'False',
00502                        'color_line'      : 'red',
00503                        'distance_circle' : '100',
00504                        'pattern'         : 'circle',
00505                        'locale'          : 'NULL',
00506                        'locale_sound'    : 'NULL'
00507                        }
00508     return default_config
00509 
00510