示例#1
0
 def _splash_controls(self):
     Img.screen.fill((0,0,0))
     txt = _("Use these keys on your keyboard to control the bat.")
     txtlist = utils.txtfmt([txt],36)
     s1,spam = utils.text2surf(txtlist[0],18,GREEN, bold=True)
     s2,spam = utils.text2surf(txtlist[1],18,GREEN, bold=True)
     Img.screen.blit(s1,(100,200))
     Img.screen.blit(s2,(100,240))
     pygame.display.update()
     rects = []
     fsize = 24
     
     surf = pygame.Surface((60,300))
     surf.blit(utils.load_image(os.path.join(self.my_datadir,'arrow_up.png')),(4,0))
     #surf.blit(utils.load_image(os.path.join(self.my_datadir,'bat.png')),(26,120))
     surf.blit(utils.load_image(os.path.join(self.my_datadir,'arrow_down.png')),(4,240))
     surf_r = surf.convert()# copy for the right side
     
     if ONEPLAYER == 0 and PCPLAYER == 0:
         surf.blit(utils.char2surf(self.rc_dic['left_keyup'].upper(),fsize,GREEN, bold=True),(16,70))
         surf.blit(utils.char2surf(self.rc_dic['left_keydown'].upper(),fsize,GREEN, bold=True),(16,190))
     surf_r.blit(utils.char2surf(self.rc_dic['right_keyup'].upper(),fsize,GREEN, bold=True),(16,70))
     surf_r.blit(utils.char2surf(self.rc_dic['right_keydown'].upper(),fsize,GREEN, bold=True),(16,190))
     rects.append(Img.screen.blit(surf,(40,100)))
     rects.append(Img.screen.blit(surf_r,(700,100)))
     pygame.display.update(rects)
     pygame.time.wait(4000)
     self.skipssplash = 1
示例#2
0
 def update(self):
     rects = []
     sr = self.black.convert()
     sr.blit(utils.char2surf(str(self.score[1]),self.size,GREEN),(0,0))
     sl = self.black.convert()
     sl.blit(utils.char2surf(str(self.score[0]),self.size,GREEN),(0,0))
     rects.append(Img.screen.blit(sl,(self.pos_l)))
     rects.append(Img.screen.blit(sr,(self.pos_r)))
     rects.append(Img.backgr.blit(sl,(self.pos_l)))
     rects.append(Img.backgr.blit(sr,(self.pos_r)))
     pygame.display.update(rects)
     if self.end in self.score:
         # hack to erase the sprite. Because the position of the sprite is changed
         # after it's drawn on the screen. So we must erase it's 'old' position.
         Misc.ball.rect = Misc.ball.oldrect
         Misc.ball.erase_sprite()
         pygame.time.wait(3000)
         if self.score[0] == self.end:
             Winner('left')
             Loser('right')
         else:
             Winner('right')
             Loser('left')
         pygame.time.wait(9500)
         # End of this game
         self.score = (0,0)
         self.update()
示例#3
0
 def draw(self):
     if self.password_mode:
         self.messagesurf = utils.char2surf('*' * len(self.message) +'_', self.fsize, self.fgcol, bold=self.bold)
     else:
         self.messagesurf = utils.char2surf(self.message+'_', self.fsize, self.fgcol, bold=self.bold)
     if self.messagesurf.get_size()[0] <= self.length:
         self.image.blit(self.orgimage, (0, 0))
         self.image.blit(self.messagesurf, (self.xpadding, self.ypadding))
     else:
         self.message = self.message[:-1]
     self.display_sprite()
示例#4
0
 def __init__(self, path, hpath, text, pos=(0, 0), textpos=2, padding=4, fsize=24,\
               fgcol=BLACK, name='', **kwargs):
     """Button which shows an image and text.
     path - must be the path to the image file.
     hpath - 'rollover' image path.
     pos - position to display the box
     rect - Rect indicating the size of the box
     padding - space in pixels around the text
     name - string to indicate this object
     text - text to display. String will be split on \n.
     textpos - position of the text, 1 means left from the image, 2 means right from the image
     """
     image = utils.load_image(path)
     imageh = utils.load_image(hpath)
     surflist = []
     surfhlist = []
     for line in text.split('\n'):
         if line == '':
             line = ' '
         surflist.append(utils.char2surf(line, fcol=fgcol, fsize=fsize, ttf=TTF))
         surfhlist.append(utils.char2surf(line, fcol=GREY, fsize=fsize, ttf=TTF))
     w = max([s.get_width() for s in surflist])
     h = surflist[0].get_height() 
     totalh = h * len(surflist)
     textsurf = pygame.Surface((w, totalh), SRCALPHA)
     y = 0
     for s in surflist:
         textsurf.blit(s, (0, y))
         y += h
     textsurf_h = pygame.Surface((w, totalh), SRCALPHA)
     y = 0
     for s in surfhlist:
         textsurf_h.blit(s, (0, y))
         y += h
     w = image.get_width() + w + padding * 2
     h = max(image.get_height(),  totalh)
     surf = pygame.Surface((w, h), SRCALPHA)
     hsurf = surf.copy()
     image_y = (surf.get_height() - image.get_height()) / 2
     text_y = (surf.get_height() - textsurf.get_height()) / 2
     if textpos == 1:
         surf.blit(textsurf, (0, text_y))
         surf.blit(image, (textsurf.get_width() + padding, image_y))
         hsurf.blit(textsurf_h, (0, text_y))
         hsurf.blit(imageh, (textsurf_h.get_width() + padding, image_y))
     else:
         surf.blit(image, (0, image_y))
         surf.blit(textsurf, (image.get_width() + padding, text_y))
         hsurf.blit(imageh, (0, image_y))
         hsurf.blit(textsurf_h, (imageh.get_width() + padding, text_y))
     
     TransImgButton.__init__(self, surf, hsurf, pos=pos, padding=padding, \
                                 fsize=fsize, fcol=fgcol, name=name)
示例#5
0
 def pre_level(self, level):
     """Mandatory method.
     Return True to call the eventloop after this method is called."""
     self.logger.debug("pre_level called with: %s" % level)
     if not self.runme:
         return
     self.SPG.tellcore_disable_level_indicator()
     self.SPG.tellcore_disable_score_button()
     self.screen.blit(self.backsquare, (50, 110))
     txt = [
         _("If you ready to start the next activity, hit the 'start' button."
           )
     ]
     txt = utils.txtfmt(txt, 40)
     y = 200
     for t in txt:
         surf = utils.char2surf(t, 28, WHITE)
         r = self.screen.blit(surf, (80, y))
         pygame.display.update(r)
         y += 50
     startbutpath = utils.load_image(
         os.path.join(self.my_datadir, 'start.png'))
     startbutpath_ro = utils.load_image(
         os.path.join(self.my_datadir, 'start_ro.png'))
     self.startbutton = SPWidgets.TransImgButton(startbutpath, startbutpath_ro, \
                                 (300, 350), fsize=32, text= _("Start"), fcol=WHITE)
     self.startbutton.connect_callback(self._cbf, MOUSEBUTTONDOWN, 'start')
     self.startbutton.set_use_current_background(True)
     self.startbutton.display_sprite()
     self.actives.add(self.startbutton)
     self.start_loop_flag = True
     self.PB.update()
     return True
示例#6
0
 def __init__(self, c, x, y, step, delay):
     # create a image of the character c
     size = 48
     effect_amt = 6
     rectsizex, rectsizey = 80, 80
     r, g, b = 255, 0, 0
     #self.image= utils.shadefade(c,size,effect_amt,(rectsizex,rectsizey),(r,g,b))
     self.image = utils.char2surf(c, size, fcol=RED, bold=True)
     SPSpriteUtils.SPSprite.__init__(self,
                                     self.image)  # embed it in this class
     self.letter = c
     start = (x, y)
     self.delay = delay
     self.wait = delay
     self.rect = self.image.get_rect()
     end = (x, 600)  # move of the screen
     loop = 0  # 0 means one time, 1 means twice
     # setup the movement of this object and get a reference to the iterator
     # which we need in the on_update method.
     self.moveit = self.set_movement(start, end, step, 0, loop)
     self.connect_callback(self.callback, event_type=KEYDOWN)
     # counter that holds the number of on_update calls.
     # It is used to calculate the score value.
     # The bigger the counter the longer the object was visible
     self.visibletime = 0
示例#7
0
 def __init__(self, txt, pos=(0, 0), fsize=18, padding=4, name='', fbold=True, **kwargs):
     """Button which shows a text
     txt - string to display
     pos - position to display the box
     fsize - Font size
     padding - space in pixels around the text
     name - string to indicate this object
     kwargs - bgcol, fgcol
     """
     Widget.__init__(self)
     if kwargs.has_key('fgcol'):
         fgcol = kwargs['fgcol']
     else:
         fgcol = self.THEME['button_fg_color']
     self.kwargs = kwargs
     self.ImSelected = False
     if type(txt) in (types.StringType, types.UnicodeType):
         s = utils.char2surf(txt, fcol=fgcol, fsize=fsize, ttf=TTF, bold=fbold)
         r = s.get_rect()
         r.w += padding*2
         r.h += padding*2
     else:
         s = txt
         r = s.get_rect()
         r.w += padding*2
         r.h += padding*2
     if kwargs.has_key('maxlength') and r.w > kwargs['maxlength']:
         r.w = kwargs['maxlength']
     self.pos = pos
     self.padding = padding
     self.name = name
     self.r = r
     self._setup(s)
示例#8
0
 def __init__(self, text, surf):
     self.image = surf
     tsurf = utils.char2surf(text, fsize=14, fcol=BLACK)
     self.image.blit(tsurf, (10, 3))
     SPSpriteUtils.SPSprite.__init__(self, self.image)
     self.moveto((0, 500))
     self.set_use_current_background(True)
 def on_git_pull_clicked(self, *args):
     self.logger.debug("git_pull called")
     self.screen.blit(self.surf, (25, 25))
     # If we have network troubles, the smtp client timesout in 10 seconds.
     line = _("Git is updating your code, please wait.....")
     s = utils.char2surf(line, fsize=24, fcol=DARKGREEN,bold=True)
     self.screen.blit(s, (50, 300))
     pygame.display.update()
     process = subprocess.Popen(['git checkout %s & git pull' % GITBRANCH], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
     txt = list(process.communicate())
     # we run a script which could contain stuff needed after a git update.
     self.logger.debug("Run scripts from post_pull directory, if any.")
     pp_txt = self._run_post_pull()
     self.logger.debug(pp_txt)
     txt += pp_txt
     result = -3
     txt.append("\nThe system will be restarted with the current commandline options.")
     txtlist = [s for s in txt if s]
     if len(txtlist) > 13:
         txtlist = txtlist[:-40]
     txt = '\n'.join(txtlist)
     dlg = SPWidgets.Dialog(txt, dialogwidth=500, buttons=["OK"], title='Information',fsize=8)
     dlg.run()
     self.on_quit_clicked()
     return result
示例#10
0
 def _mail_logfile(self, logpath='', imgpath=''):
     self.logger.debug("_mail_logfile called")
     data = self._get_entrydata()
     result = self._validate_data(data)
     if result:
         dlg = SPWidgets.Dialog("The following entries are empty or have to little text:\n%s" % result,dialogwidth=500,  \
                 buttons=["OK"], title='Error !')
         dlg.run()
         return
     
     self.screen.blit(self.surf, (25, 25))
     # If we have network troubles, the smtp client timesout in 10 seconds.
     line = _("Your email will be send, please wait.....")
     s = utils.char2surf(line, fsize=24, fcol=DARKGREEN,bold=True)
     self.screen.blit(s, (50, 300))
     pygame.display.update()
     
     try:
         Mail.mail(subject=data['short'], description=data['long'], \
                   component=data['component'], prio=data['prio'], \
                   assigned=data['assigned'], milestone=data['milestone'], \
                   name=data['name'], \
                   logpath=logpath, imgpath=imgpath)
     except Mail.SendmailError,err:
         self.activity_info_dialog(_("Failed to send the email. Error: %s") % err)
示例#11
0
 def settext(self, txt):
     self._txt = txt
     s = utils.char2surf(txt,
                         fsize=self.fsize,
                         ttf=self.ttf,
                         fcol=self.fgcol,
                         bold=self.bold)
     r = s.get_rect()
     if self.minh:
         y = self.minh
         x = r.w
         x += self.padding * 2
         surf = pygame.Surface((x, y))
     else:
         x = r.w
         x += self.padding * 2
         y = r.h
         y += self.padding * 2
         surf = pygame.Surface((x, y))
     x = (surf.get_rect().w - r.w) / 2
     y = (surf.get_rect().h - r.h) / 2
     surf.fill(self.bgcol)
     surf.blit(s, (x, y))
     if self.transparent:
         self.image = s
     else:
         self.image = surf
     if self.border:
         pygame.draw.rect(self.image, BLACK, self.image.get_rect(),
                          self.border)
示例#12
0
 def __update(self):
     if self.__clock_stopped:
         return
     if self.__minutes == self.__endminutes and \
         self.__seconds == self.__endseconds:
         if self.__alarm:
             try:
                 apply(self.__alarm)
             except Exception:
                 self.logger.exception("Exception in %s" % self.__class__)
             self.__clock.stop()
             self.__clock_stopped = 1
             return
     if self.__count == 1:# forwards
         if self.__seconds == 59:
             self.__seconds = 0
             self.__minutes += self.__count
         else:
             self.__seconds += self.__count
     else:# backwards
         if self.__seconds == 0:
             self.__seconds = 59
             self.__minutes += self.__count
         else:
             self.__seconds += self.__count
     time = "%02d:%02d" % (self.__minutes, self.__seconds)
     self.__tsprite.erase_sprite()
     self.erase_sprite()
     self.image = char2surf(time, self.__csize, self.__ccol)
     self.display_sprite()
     self.__tsprite.display_sprite()
     return 1
示例#13
0
    def _setup(self):
        # get all the surfaces
        title = utils.char2surf(self.title,
                                24,
                                ttf=TTF,
                                fcol=self.THEME['dialog_title_fg_color'],
                                bold=True)

        if type(self.txt) == types.ListType or type(
                self.txt) in types.StringTypes:
            tv = TextView(self.txt, (0, 0), pygame.Rect(0, 0, self.dialogwidth, 400),\
                           bgcol='trans',fsize=self.fsize ,\
                          fgcol=self.THEME['dialog_fg_color'], autofit=True, bold=self.fbold)
        else:  # we assume a SPWidget.Widget object
            tv = self.txt
        b = self.buttons_list[0]
        # start building dialog
        if self.dialogwidth and self.dialogheight:
            r = pygame.Rect(0, 0, self.dialogwidth, self.dialogheight)
        else:
            r = pygame.Rect(0, 0, max(self.butspace,(tv.rect.w + (self.padding * 2)),100), \
                        title.get_rect().h + 8 + b.rect.h + tv.rect.h + (self.padding*3))
        if r.w > 750:
            r.w = 750
        if r.h > 530:
            r.h = 530
        dlgsurf, dlgsizes = make_dialog_bg_dynamic(r.w + 50, r.h + 70,
                                                   self.THEME)

        r = dlgsurf.get_rect()
        if not self.pos:
            y = max(10, (600 - r.h) / 2)
            x = (800 - r.w) / 2
            self.pos = (x, y)

        y = 10
        x = 20
        dlgsurf.blit(title, (x, y))
        dlgsurf.blit(tv.image, (x, dlgsizes['title_area'].h))

        Widget.__init__(self, dlgsurf)

        self.image = dlgsurf

        self.rect.move_ip(self.pos)
        for k, v in dlgsizes.items():
            dlgsizes[k].move_ip(self.pos)
        x = self.rect.left + (
            (self.rect.w - (self.butspace + 16 * len(self.buttons_list))) / 2)
        y = self.rect.bottom - self.buttons_list[0].rect.h * 2
        if len(self.buttons_list) == 2:
            x = self.rect.left + 16
            self.buttons_list[0].moveto((x, y), True)
            x = self.rect.right - (self.buttons_list[1].rect.w + 16)
            self.buttons_list[1].moveto((x, y), True)
        else:
            for b in self.buttons_list:
                b.moveto((x, y), True)
                x += b.rect.w + 16
        self.dlgsizes = dlgsizes
示例#14
0
 def __init__(self, text, surf):
     self.image = surf
     tsurf = utils.char2surf(text, fsize=14, fcol=BLACK)
     self.image.blit(tsurf, (10, 3))
     SPSpriteUtils.SPSprite.__init__(self, self.image)
     self.moveto((0, 500))
     self.set_use_current_background(True)
示例#15
0
 def settext(self, txt):
     self._txt = txt
     s = utils.char2surf(txt, fsize=self.fsize,ttf=self.ttf, fcol=self.fgcol, bold=self.bold)
     r = s.get_rect()
     if self.minh:
         y = self.minh
         x = r.w
         x += self.padding*2
         surf = pygame.Surface((x, y))
     else:
         x = r.w
         x += self.padding*2
         y = r.h
         y += self.padding*2
         surf = pygame.Surface((x, y))
     x = (surf.get_rect().w - r.w) / 2
     y = (surf.get_rect().h - r.h) / 2
     surf.fill(self.bgcol)
     surf.blit(s, (x, y))
     if self.transparent:
         self.image = s
     else:
         self.image = surf
     if self.border:
         pygame.draw.rect(self.image, BLACK, self.image.get_rect(), self.border)
示例#16
0
    def _mail_logfile(self, logpath='', imgpath=''):
        self.logger.debug("_mail_logfile called")
        data = self._get_entrydata()
        result = self._validate_data(data)
        if result:
            dlg = SPWidgets.Dialog("The following entries are empty or have to little text:\n%s" % result,dialogwidth=500,  \
                    buttons=["OK"], title='Error !')
            dlg.run()
            return

        self.screen.blit(self.surf, (25, 25))
        # If we have network troubles, the smtp client timesout in 10 seconds.
        line = _("Your email will be send, please wait.....")
        s = utils.char2surf(line, fsize=24, fcol=DARKGREEN, bold=True)
        self.screen.blit(s, (50, 300))
        pygame.display.update()

        try:
            Mail.mail(subject=data['short'], description=data['long'], \
                      component=data['component'], prio=data['prio'], \
                      assigned=data['assigned'], milestone=data['milestone'], \
                      name=data['name'], \
                      logpath=logpath, imgpath=imgpath)
        except Mail.SendmailError, err:
            self.activity_info_dialog(
                _("Failed to send the email. Error: %s") % err)
示例#17
0
 def on_git_pull_clicked(self, *args):
     self.logger.debug("git_pull called")
     self.screen.blit(self.surf, (25, 25))
     # If we have network troubles, the smtp client timesout in 10 seconds.
     line = _("Git is updating your code, please wait.....")
     s = utils.char2surf(line, fsize=24, fcol=DARKGREEN, bold=True)
     self.screen.blit(s, (50, 300))
     pygame.display.update()
     process = subprocess.Popen(['git checkout %s & git pull' % GITBRANCH],
                                shell=True,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
     txt = list(process.communicate())
     # we run a script which could contain stuff needed after a git update.
     self.logger.debug("Run scripts from post_pull directory, if any.")
     pp_txt = self._run_post_pull()
     self.logger.debug(pp_txt)
     txt += pp_txt
     result = -3
     txt.append(
         "\nThe system will be restarted with the current commandline options."
     )
     txtlist = [s for s in txt if s]
     if len(txtlist) > 13:
         txtlist = txtlist[:-40]
     txt = '\n'.join(txtlist)
     dlg = SPWidgets.Dialog(txt,
                            dialogwidth=500,
                            buttons=["OK"],
                            title='Information',
                            fsize=8)
     dlg.run()
     self.on_quit_clicked()
     return result
示例#18
0
 def __init__(self, path, hpath, pos=(0, 0), padding=4,text='',fsize=24, fcol=BLACK, name='', **kwargs):
     """Button which shows an image but has a fully transparent background.
     When a hover event occurs the image is changed.
     path - must be the path to the image file or a pygame surface
     hpath - must be the path to the image file or a pygame surface that will
             be shown when a hover event occurs.
     pos - position to display the box
     rect - Rect indicating the size of the box
     padding - space in pixels around the text
     name - string to indicate this object
     text - when a sting is given it will be blitted over the image.
     fsize - fontsize.
     """
     self.text = text
     self.fsize = fsize
     if type(path) in types.StringTypes:
         image = utils.load_image(path)
     else:
         image = path
     if hpath:
         if type(hpath) in types.StringTypes:
             self.hs = utils.load_image(hpath)
         else:
             self.hs = hpath
     else:
         self.hs = utils.grayscale_image(image.convert_alpha())
     if self.text:
         s = utils.char2surf(text, fsize, fcol)
         r = image.get_rect()
         sr = s.get_rect()
         sr.center = r.center
         image.blit(s, sr)
         self.hs.blit(s, sr)
     ImgButton.__init__(self, image, pos, padding=padding, name=name)
示例#19
0
 def pre_level(self,level):
     """Mandatory method.
     Return True to call the eventloop after this method is called."""
     self.logger.debug("pre_level called with: %s" % level)
     self.pre_level_flag = True
     Img.screen.fill((0,0,0))
     pygame.display.update()
     # Display the three choices of game play.
     # This will put the menu items in the actives group which then will be updated
     # in the game loop. When the users picks one the result will be handled by
     # the restart method.
     self.choice = None # will be set in loop
     # FIXME: disabled the pc pclayer as it's not working right.
     # The bats are not moving smoothly whit the pcplayer.
     # The same problem exists when playing with two players but it's less annoying 
     positions = [(130,70),(130,220)]#,(130,370)]
     images = ('single.jpg','multi_person.jpg')#,'multi_pc.jpg')
     head = _("Choose the game to play:")
     s = utils.char2surf(head,32,GREEN, bold=True)
     pygame.display.update(Img.screen.blit(s,(80,4)))
     for pos,img,data in map(None,positions,images,('1','2')):
         img = os.path.join(self.my_datadir,img)
         obj = SPSpriteUtils.SPButton(utils.load_image(img),pos,data)
         self.actives.add(obj)
         obj.display_sprite() 
     return True
示例#20
0
 def __init__(self, pos, total, fsize=10, text=''):
     """The width of the widget is determined by the width of the headertext
     with a minimal width of four spaces and a maximum of fourteen characters.
     total - the total number of exercises.
     fsize - Fontsize for the text
     text - Headertext defaults to 'Exercises' (localized)
     """
     self.logger = logging.getLogger("childsplay.SPocwWidgets.ExeCounter")
     Widget.__init__(self)
     self.total = total
     self.done = 0
     if not text:
         text = _("Exercises")
     if len(text) > 14:#prevent to large label when localized
         text = text[:14]
     fgcol=self.THEME['execounter_fg_color']
     bgcol = self.THEME['execounter_bg_color']
     s0 = utils.char2surf(text, fsize=fsize, fcol=fgcol)
     txt = "%s/%s" % (self.done, self.total)
     
     self.lbl = Label(txt, (pos[0]+2, pos[1]+s0.get_height()), fsize=12, padding=4, border=0, fgcol=fgcol, bgcol=bgcol)
     
     r = pygame.Rect(0, 0,s0.get_rect().w+4, s0.get_rect().h +\
                                            self.lbl.rect.h+4)
     box, spam = get_boxes(bgcol, BLACK, r)
     
     box.blit(s0, (2, 2))
     self.image = box       
     Widget.__init__(self, box)
     self.rect.move_ip(pos)
     self.display_sprite()
     self.lbl.display_sprite()
示例#21
0
 def pre_level(self,level):
     """Mandatory method.
     Return True to call the eventloop after this method is called."""
     self.logger.debug("pre_level called with: %s" % level)
     if not self.runme:
         return
     self.SPG.tellcore_disable_level_indicator()
     self.SPG.tellcore_disable_score_button()
     self.screen.blit(self.backsquare, (50, 110))
     txt = [_("If you ready to start the next activity, hit the 'start' button.")]
     txt = utils.txtfmt(txt, 40)
     y = 200
     for t in txt:
         surf = utils.char2surf(t,28,WHITE)
         r = self.screen.blit(surf, (80, y))
         pygame.display.update(r)
         y += 50
     startbutpath = utils.load_image(os.path.join(self.my_datadir, 'start.png'))
     startbutpath_ro = utils.load_image(os.path.join(self.my_datadir, 'start_ro.png'))
     self.startbutton = SPWidgets.TransImgButton(startbutpath, startbutpath_ro, \
                                 (300, 350), fsize=32, text= _("Start"), fcol=WHITE)
     self.startbutton.connect_callback(self._cbf, MOUSEBUTTONDOWN, 'start')
     self.startbutton.set_use_current_background(True)
     self.startbutton.display_sprite()
     self.actives.add(self.startbutton)
     self.start_loop_flag = True
     self.PB.update()
     return True 
示例#22
0
 def _remove_prompt(self):
     self.image.blit(self.orgimage, (0, 0))
     self.messagesurf = utils.char2surf(self.message,
                                        self.fsize,
                                        self.fgcol,
                                        bold=self.bold)
     self.image.blit(self.messagesurf, (self.xpadding, self.ypadding))
     self.display_sprite()
示例#23
0
 def draw(self):
     if self.password_mode:
         self.messagesurf = utils.char2surf('*' * len(self.message) + '_',
                                            self.fsize,
                                            self.fgcol,
                                            bold=self.bold)
     else:
         self.messagesurf = utils.char2surf(self.message + '_',
                                            self.fsize,
                                            self.fgcol,
                                            bold=self.bold)
     if self.messagesurf.get_size()[0] <= self.length:
         self.image.blit(self.orgimage, (0, 0))
         self.image.blit(self.messagesurf, (self.xpadding, self.ypadding))
     else:
         self.message = self.message[:-1]
     self.display_sprite()
示例#24
0
 def __init__(self, txt, pos, rect=None, fsize=12, padding=4, \
              autofit=False, border=False, name='', \
              bgcol=None, fgcol=None, shade=0, bold=False, **kwargs):
     """Box which displays a text, wrapped if needed. 
     txt - string to display. When txt is a list of strings the lines are
         blitted on a surface big enough to hold the longest line.
         rect is not used in this case.
     pos - position to display the box
     rect - Rect indicating the size of the box. 
             Only used in conjunction with txt if it's a string.
     fsize - Font size
     padding - space in pixels around the text
     fgcol - text color (R,G,B), if None the theme color will be used.
     bgcol - background color (R,G,B), if None the theme color will be used.
             If bgcol is set to 'trans' the background will be transparent.
     autofit - Discard the empty space around the text.
     name - string to indicate this object
     shade - The amount of "3D shade" the text should have, 0 means no shade.
             Beware that shading takes time.
     """
     if not fgcol: 
         fgcol = self.self.THEME['textview_fg_color']
     if not bgcol:
         bgcol = self.self.THEME['textview_bg_color']
     if type(txt) in types.StringTypes and rect != None:
         self.image = render_textrect(txt, fsize, TTF, rect, fgcol, \
                           bgcol, justification=0, bold=bold, \
                           autofit=autofit, border=border)
     elif type(txt) is types.ListType:
         ll = []
         w = 0
         for line in txt:
             if not line.strip('\n'):
                 line = ' '
             if shade:
                 s = utils.shadefade(line, fsize, amount=shade, bold=bold, fcol=fgcol, shadecol=DARKGREY)
                 ll.append(s)
             else:
                 s = utils.char2surf(line, fsize, fgcol, bold=bold)
                 ll.append(s)
             if s.get_rect().w > w:
                 w = s.get_rect().w
             
         h = s.get_rect().h   
         if bgcol == 'trans':
             self.image = pygame.Surface((w, h * len(ll)), SRCALPHA)
             self.image.fill((0, 0, 0, 0))
         else:
             self.image = pygame.Surface((w, h * len(ll)))
             self.image.fill(bgcol)
         x, y = 0, 0
         for s in ll:
             self.image.blit(s, (x, y))
             y += h
         
     self.rect  = self.image.get_rect()
     Widget.__init__(self, self.image)
     self.rect.move_ip(pos)       
示例#25
0
    def __init__(self, txt, pos, rect=None, fsize=12, padding=4, \
                 autofit=False, border=False, name='', \
                 bgcol=None, fgcol=None, shade=0, bold=False, **kwargs):
        """Box which displays a text, wrapped if needed. 
        txt - string to display. When txt is a list of strings the lines are
            blitted on a surface big enough to hold the longest line.
            rect is not used in this case.
        pos - position to display the box
        rect - Rect indicating the size of the box. 
                Only used in conjunction with txt if it's a string.
        fsize - Font size
        padding - space in pixels around the text
        fgcol - text color (R,G,B), if None the theme color will be used.
        bgcol - background color (R,G,B), if None the theme color will be used.
                If bgcol is set to 'trans' the background will be transparent.
        autofit - Discard the empty space around the text.
        name - string to indicate this object
        shade - The amount of "3D shade" the text should have, 0 means no shade.
                Beware that shading takes time.
        """
        if not fgcol:
            fgcol = self.self.THEME['textview_fg_color']
        if not bgcol:
            bgcol = self.self.THEME['textview_bg_color']
        if type(txt) in types.StringTypes and rect != None:
            self.image = render_textrect(txt, fsize, TTF, rect, fgcol, \
                              bgcol, justification=0, bold=bold, \
                              autofit=autofit, border=border)
        elif txt and type(txt) is types.ListType:
            ll = []
            w = 0
            for line in txt:
                if not line.strip('\n'):
                    line = ' '
                s = utils.char2surf(line, fsize, fgcol, bold=bold)
                ll.append(s)
                if s.get_rect().w > w:
                    w = s.get_rect().w

            h = s.get_rect().h
            if bgcol == 'trans':
                self.image = pygame.Surface((w, h * len(ll)), SRCALPHA)
                self.image.fill((0, 0, 0, 0))
            else:
                self.image = pygame.Surface((w, h * len(ll)))
                self.image.fill(bgcol)
            x, y = 0, 0
            for s in ll:
                self.image.blit(s, (x, y))
                y += h

        self.rect = self.image.get_rect()
        Widget.__init__(self, self.image)
        self.rect.move_ip(pos)
示例#26
0
 def set_text(self, text):
     """Add one line of text."""
     self.prevlines.append(text)
     if len(self.prevlines) > self.lines:
         self.prevlines = self.prevlines[-self.lines:]
     self.image.blit(self.org_image, (0, 0))
     y = 0
     for line in self.prevlines:
         surf = utils.char2surf(line, self.fsize, self.fgcol)
         self.image.blit(surf, (self.padding, self.padding + y))
         y += surf.get_height()
示例#27
0
 def set_text(self, text):
     """Add one line of text."""
     self.prevlines.append(text)
     if len(self.prevlines) > self.lines:
         self.prevlines = self.prevlines[-self.lines:]
     self.image.blit(self.org_image, (0, 0))
     y = 0
     for line in self.prevlines:
         surf = utils.char2surf(line, self.fsize, self.fgcol)
         self.image.blit(surf, (self.padding, self.padding + y))
         y += surf.get_height()
示例#28
0
    def __init__(self, value, pos, obs, fsize=28, butsize=(48, 48)):
        ci = utils.char2surf(value, fsize, WHITE, ttf=TTFBOLD)
        s = pygame.Surface(butsize)
        s.fill(KEYCOL)
        pygame.draw.rect(s, WHITE, s.get_rect(), 1)
        cir = ci.get_rect()
        cir.center = s.get_rect().center
        s.blit(ci, cir)

        SuperKey.__init__(self, s, pos, 4, value)
        self.connect_callback(obs, MOUSEBUTTONUP, value)
示例#29
0
    def _setup(self):
        # get all the surfaces
        title = utils.char2surf(self.title, 24, ttf=TTF, fcol=self.THEME['dialog_title_fg_color'], bold=True)
        
        if type(self.txt) == types.ListType or type(self.txt) in types.StringTypes:
            tv = TextView(self.txt, (0, 0), pygame.Rect(0, 0, self.dialogwidth, 400),\
                           bgcol='trans',fsize=self.fsize ,\
                          fgcol=self.THEME['dialog_fg_color'], autofit=True, bold=self.fbold)
        else: # we assume a SPWidget.Widget object
            tv = self.txt
        b = self.buttons_list[0]
        # start building dialog
        if self.dialogwidth and self.dialogheight:
            r = pygame.Rect(0, 0, self.dialogwidth, self.dialogheight)
        else:
            r = pygame.Rect(0, 0, max(self.butspace,(tv.rect.w + (self.padding * 2)),100), \
                        title.get_rect().h + 8 + b.rect.h + tv.rect.h + (self.padding*3))
        if r.w > 750:
            r.w = 750
        if r.h > 530:
            r.h = 530
        dlgsurf, dlgsizes = make_dialog_bg_dynamic(r.w+50, r.h+70, self.THEME)
        
        r = dlgsurf.get_rect()
        if not self.pos:
            y = max(10, (600 - r.h) / 2)
            x = (800 - r.w) / 2
            self.pos = (x, y)

        y = 10
        x = 20
        dlgsurf.blit(title, (x,y))
        dlgsurf.blit(tv.image, (x, dlgsizes['title_area'].h))
        
        Widget.__init__(self, dlgsurf)
        
        self.image = dlgsurf

        self.rect.move_ip(self.pos)
        for k, v in dlgsizes.items():
            dlgsizes[k].move_ip(self.pos)
        x = self.rect.left + ((self.rect.w - (self.butspace + 16 * len(self.buttons_list))) / 2)
        y = self.rect.bottom - self.buttons_list[0].rect.h *2
        if len(self.buttons_list) == 2:
            x = self.rect.left + 16
            self.buttons_list[0].moveto((x, y), True)
            x = self.rect.right - (self.buttons_list[1].rect.w + 16)
            self.buttons_list[1].moveto((x, y), True)
        else:
            for b in self.buttons_list:
                b.moveto((x, y), True)
                x += b.rect.w + 16
        self.dlgsizes = dlgsizes
示例#30
0
 def next_exercise(self, currentletter=None):
     self.logger.debug("next_exercise called")
     self.found = []
     if not currentletter:
         if len(self.sequence) > 1:
             self.currentletter = self.sequence.pop()
         else: 
             self.sequence = self.alfabet[:]
             random.shuffle(self.sequence)
             self.currentletter = self.sequence.pop()
     self.screen.blit(self.background, (self.x, self.y))
     self.backgr.blit(self.background, (self.x, self.y))
     
     self.wc.set_firstletter(self.currentletter)
     self.kb._set_firstletter(self.currentletter, self.wrong_sound)
     self.kb.show()
             
     qs = utils.char2surf(self.questiontext, fsize=24, fcol=self.fgcol)
     r = self.screen.blit(qs,(self.texttop_pos[0], self.texttop_pos[1]))
     ls_pos = (r.topright[0], r.topright[1]-4)
     
     s = utils.char2surf(self.foundtext, fsize=20, fcol=self.fgcol)
     self.screen.blit(s, self.textright_pos)
     pygame.display.update()
     #### Start animation, increase or decrease attribute value from pygame.time.wait
     for i in range(4, 32):
         s = utils.char2surf(self.currentletter.upper(), fsize=i, fcol=RED, bold=True)
         r = self.screen.blit(s, ls_pos)
         pygame.display.update(r)
         pygame.time.wait(10)
         pygame.display.update(self.screen.blit(self.backgr, r, r))
     s = utils.char2surf(self.currentletter.upper(), fsize=i, fcol=self.fgcol, bold=True)
     r = self.screen.blit(s, ls_pos)
     pygame.display.update(r)
     #########################################################
     self.actives.add(self.newquestionbut)
     self.newquestionbut.display_sprite()
     
     self.wc_x,  self.wc_y = self.wc_pos
示例#31
0
 def _on_lbl_clicked(self, lbl, event, txt):
     found_width = 250
     #self.logger.debug("_on_lbl_clicked called")
     if not self.wc.lookup(txt[0]):
         self.logger.debug("%s not in dictionary" % txt[0])
         self.wrong_sound.play()
         return
     self.found.append(txt[0])
     if len(self.found) > 17:
         # fake a button event
         self._on_newquestionbut_clicked()
         return
     self.actives.remove(lbl)
     if self.suggest_lbl.has_key(lbl._txt):
         del self.suggest_lbl[lbl._txt]
         lbl.erase_sprite()
     # check to see if we will fit in the 'already found' section
     if lbl.get_sprite_width() > found_width:
         fgcol = THEME['label_fg_color']
         txt = lbl.get_text()
         txt = txt[:-6] + '...'
         s = utils.char2surf(txt,fsize=lbl.fsize,ttf=TTF, fcol=lbl.fgcol, bold=lbl.bold)
         if s.get_size()[0] > found_width:
             for i in range(6):
                 txt = txt[:-4] + '...'
                 s = utils.char2surf(txt,fsize=lbl.fsize,ttf=TTF, fcol=lbl.fgcol, bold=lbl.bold)
                 if s.get_size()[0] < found_width:
                     break
         lbl.settext(txt)    
         
     lbl.display_sprite((self.found_x, self.found_y))
     self.found_y = self.found_y + lbl.get_sprite_height() - 8
     self.good_sound.play()
     self.kb.clear_display()
     if self.suggest_lbl:
         self.actives.remove(self.suggest_lbl.values())
         for lbl in self.suggest_lbl.values():
             lbl.erase_sprite()
     self.suggest_lbl = {}
示例#32
0
def GameResult(player, screen):
    global n_player
    global n_computer
    if player == 0:
        text = "The Computer Won!!!"
        n_computer += 1
    if player == 1:
        text = "The Player Won!!!"
        n_player += 1
    if player == 2:
        text = "The Game is Tie!!!"
    surf = utils.char2surf(text, 72, BLACK)
    screen.blit(surf, (100, 300))
    pygame.display.flip()
    pygame.time.wait(2000)
    pygame.event.clear()
示例#33
0
    def next_level(self,level,dbmapper):
        """Mandatory method.
        Return True if there levels left.
        False when no more levels left."""
        self.logger.debug("nextlevel called with: %s" % level)
        # Your top blit position, this depends on the menubar position 
        if self.blit_pos[1] == 0:
            y = 10
        else:
            y = 110
        self.level = level
        self.dbmapper = dbmapper
        # Remove these four lines
        text = "Template activity for " + self.get_helptitle()
        surf = utils.char2surf(text,24,RED)
        self.screen.blit(surf,(20,200))
        pygame.display.flip()

        return True
示例#34
0
    def __init__(self, pos, obs, fsize=28, butsize=(100, 104)):
        text = utils.char2surf("Enter", fsize, WHITE, ttf=TTFBOLD)
        textpos = text.get_rect()
        s = pygame.Surface(butsize)
        s.fill(KEYCOL)
        sr = s.get_rect()
        blockoffx = (sr.width / 2)
        blockoffy = (sr.height / 2)
        offsetx = blockoffx - (textpos.width / 2)
        offsety = blockoffy - (textpos.height / 2) + 8
        s.blit(text, (offsetx, (offsety - 30)))

        pygame.draw.rect(s, WHITE, s.get_rect(), 1)
        pygame.draw.line(s, WHITE, (80, 71), (80, 81), 2)
        pygame.draw.line(s, WHITE, (80, 81), (25, 81), 2)
        pygame.draw.line(s, WHITE, (25, 81), (30, 76), 2)
        pygame.draw.line(s, WHITE, (25, 82), (30, 87), 2)

        SuperKey.__init__(self, s, pos, 4, 'enter')
        self.connect_callback(obs, MOUSEBUTTONUP, 'enter')
示例#35
0
 def _draw_field(self):
     Img.screen.fill((0,0,0))
     Img.backgr.fill((0,0,0))
     
     box = pygame.Rect(0,0,800,500).inflate(-32,-32)
     #box.inflate(-32,-32)
     pygame.draw.rect(Img.screen,\
                      GREEN,\
                      box,\
                      4)
     pygame.draw.line(Img.screen,\
                       GREEN,\
                       (398,16),\
                       (398,484),\
                       4)
     pygame.draw.line(Img.backgr,\
                       GREEN,\
                       (398,16),\
                       (398,484),\
                       4)
     txt = _("Hit the Escape key to stop.")
     s = utils.char2surf(txt, 18, GREEN, bold=True)
     Img.screen.blit(s, (50, 550))
示例#36
0
    def __init__(self, pos, total, fsize=10, text=''):
        """The width of the widget is determined by the width of the headertext
        with a minimal width of four spaces and a maximum of fourteen characters.
        total - the total number of exercises.
        fsize - Fontsize for the text
        text - Headertext defaults to 'Exercises' (localized)
        """
        self.logger = logging.getLogger("childsplay.SPocwWidgets.ExeCounter")
        Widget.__init__(self)
        self.total = total
        self.done = 0
        if not text:
            text = _("Exercises")
        if len(text) > 14:  #prevent to large label when localized
            text = text[:14]
        fgcol = self.THEME['execounter_fg_color']
        bgcol = self.THEME['execounter_bg_color']
        s0 = utils.char2surf(text, fsize=fsize, fcol=fgcol)
        txt = "%s/%s" % (self.done, self.total)

        self.lbl = Label(txt, (pos[0] + 2, pos[1] + s0.get_height()),
                         fsize=12,
                         padding=4,
                         border=0,
                         fgcol=fgcol,
                         bgcol=bgcol)

        r = pygame.Rect(0, 0,s0.get_rect().w+4, s0.get_rect().h +\
                                               self.lbl.rect.h+4)
        box, spam = get_boxes(bgcol, BLACK, r)

        box.blit(s0, (2, 2))
        self.image = box
        Widget.__init__(self, box)
        self.rect.move_ip(pos)
        self.display_sprite()
        self.lbl.display_sprite()
示例#37
0
def Score(screen):
    surf = utils.char2surf("Player: " + str(n_player), 18, BLUE)
    screen.blit(surf, (20, 570))
    surf = utils.char2surf("Computer: " + str(n_computer), 18, RED)
    screen.blit(surf, (680, 570))
示例#38
0
 def next_exercise(self, currentletter=None):
     self.logger.debug("next_exercise called with %s" % currentletter)
     self.found_x, self.found_y = self.textright_pos[0], self.textright_pos[1] + 75
     if len(self.categories) < 1:
             self.categories = self.wordlisthash.keys()
             random.shuffle(self.categories)
     # Change self.newexercise_counter < 4 into 3 to get three times the same category wit a different letter. 
     if not self.currentcategory or self.newexercise_counter < 4:
         self.currentcategory = self.categories.pop()
         self.newexercise_counter = 3
     
     sequence = []
     for line in self.wordlisthash[self.currentcategory][2:]:
         c = line[1].lower()
         if c not in sequence:
             sequence.append(c)
         
     random.shuffle(sequence)
     if not currentletter:
         self.currentletter = sequence.pop()
     self.logger.debug("picked first letter %s" % self.currentletter)
     
     self.screen.blit(self.background, (self.x, self.y))
     self.backgr.blit(self.background, (self.x, self.y))
     
     self.wc.set_firstletter(self.currentletter)
     self.kb._set_firstletter(self.currentletter, self.wrong_sound)
     wordlist = self.wordlisthash[self.currentcategory][1:]
     self.wc.set_wordlist(wordlist)
     self.kb.show()
     
     h = 0
     txt = self.wordlisthash[self.currentcategory][:1][0][:-1]
     s = utils.char2surf(txt, fsize=20, fcol=self.fgcol)
     r = self.screen.blit(s,(self.texttop_pos[0], self.texttop_pos[1]+h))
     h += s.get_rect().h
     s = utils.char2surf(self.questiontext, fsize=20, fcol=self.fgcol)
     r = self.screen.blit(s,(self.texttop_pos[0], self.texttop_pos[1]+h))
     
     ls_pos = (r.topright[0], r.topright[1]-4)
     
     s = utils.char2surf(self.foundtext, fsize=20, fcol=self.fgcol)
     self.screen.blit(s, self.textright_pos)
     pygame.display.update()
     #### Start animation, increase or decrease attribute value from pygame.time.wait
     for i in range(4, 32):
         s = utils.char2surf(self.currentletter.upper(), fsize=i, fcol=RED, bold=True)
         r = self.screen.blit(s, ls_pos)
         pygame.display.update(r)
         pygame.time.wait(10)
         pygame.display.update(self.screen.blit(self.backgr, r, r))
     s = utils.char2surf(self.currentletter.upper(), fsize=i, fcol=self.fgcol, bold=True)
     r = self.screen.blit(s, ls_pos)
     pygame.display.update(r)
     ########################################################################
     self.actives.add(self.newquestionbut)
     self.newquestionbut.display_sprite()
     
     self.wc_x,  self.wc_y = self.wc_pos
     
     pygame.display.update()
示例#39
0
    def __init__(self, data, level, headertext='', norm=None):
        """@data must be a list with tuples (score,date).
        @norm is a tuple containing the mu and sigma value.
        """
        # dates are stored like this: 07-09-09_10:44:27
        # the data list is a list with tuples like (mu,sigma,date)
        self.logger = logging.getLogger("childsplay.SPWidgets_lgpl.Graph")
        # main surf is 500x300 the graph is a surf of 470x270.
        # 20 for the text bottom and left and 10 for a top and right offset
        gs = pygame.Surface((470, 270))  # surf for the graph
        gs.fill((230, 230, 230))
        self.s = pygame.Surface((500, 400))  # main surf
        self.s.fill((200, 200, 200))
        if not data:
            self.logger.warning("No data received to show in graph")
            ts = utils.char2surf(_("No data available for this level"),
                                 TTFSIZE + 8,
                                 ttf=TTF,
                                 split=35)
            y = 100
            for s in ts:
                self.s.blit(s, (20, y))
                y += s.get_height()
            Widget.__init__(self, self.s)
            return
        # border around the surf
        pygame.draw.rect(self.s, (100, 100, 100),
                         self.s.get_rect().inflate(-1, -1), 2)

        # draw mu line and sigma deviation as a transparent box.
        if norm:
            mu, sigma = norm
            # line
            pygame.draw.line(gs, DARK_BLUE, (0, 270 - mu * 27),
                             (470, 270 - mu * 27), 3)
            # deviation box, transparent blue
            top_y = mu + (mu / 100.0 * 30)
            bottom_y = mu - (mu / 100.0 * 30)
            darken = pygame.Surface((470, int((top_y - bottom_y) * 27)))
            darken.fill(BLUE)
            darken_factor = 64
            darken.set_alpha(darken_factor)
            gs.blit(darken, (0, 270 - top_y * 27))

        # draw y-axes graph lines, initial y offset is 30 pixels to leave room for text.
        i = 10
        for y in range(0, 270, 27):
            pygame.draw.line(gs, (0, 0, 0), (0, y), (470, y), 1)
            ts = utils.char2surf(str(i), TTFSIZE - 2, ttf=TTF, bold=True)
            i -= 1
            self.s.blit(ts, (4, y + 35))
        ts0 = utils.char2surf(headertext, TTFSIZE - 2, ttf=TTF, bold=True)
        ts1 = utils.char2surf(_("Percentile scores for level %s") % level,
                              TTFSIZE,
                              ttf=TTF)
        self.s.blit(ts0, (10, 2))
        self.s.blit(ts1, (20, 20))

        # Draw x-axes data
        # determine the size of the x graph steps. This depends on the number of data items.
        # as we fill the x axe. Y step is always the same as the y axe values are always 0-10.
        # The maximum is 470 items, one pixel per data item.
        x_step = 470 / len(data)
        dotslist = []
        # draw dots and x-axes lines
        for x in range(0, 471 - x_step, x_step):
            pygame.draw.line(gs, (0, 0, 0), (x, 270), (x, 0), 1)
            try:
                item = data.pop(0)
                #print item
                y = int(float(item[1]) * 27)
                #print "y position",y
                date = item[0]
                #print "date",date
            except (IndexError, TypeError):
                self.logger.exception(
                    "Troubles in the datalist, this shouldn't happen\n I try to continue but expect weird results :-)\n Traceback follows:"
                )
                continue
            else:
                pygame.draw.circle(gs, DARK_BLUE, (x + 4, 270 - y + 4), 4, 0)
                dotslist.append((x, 270 - y))
                # blit date, rotated 90 degrees clockwise
                ts = utils.char2surf(date, TTFSIZE - 5, ttf=TTF)
                # rotate 90 degrees
                v_ts = pygame.transform.rotate(ts, 270)
                self.s.blit(v_ts, (x + 20, 320))
        # connect the dots if there are more then one
        if len(dotslist) > 1:
            pygame.draw.lines(gs, BLUE, 0, dotslist, 2)
        pygame.draw.rect(gs, (0, 0, 0), gs.get_rect().inflate(-1, -1), 2)
        # finally blit the two surfaces
        self.s.blit(gs, (20, 40))
        Widget.__init__(self, self.s)
示例#40
0
 def __init__(self, start='00:00', counting=1, end='10:00',
     clocksize=32, clockpos=(0, 0), clockcolor=(0, 0, 0),
     text='', textsize=18, textcolor=(0, 0, 0), textpos=1,
     alarm=None, lock=None):
     """Timer clock. This clock depends on SpriteUtils object which is part
     of the childsplay project (http://childsplay.sf.net).
     @start is the start value of the clock in a string and must contains 
     a colon as a seperation between minutes and seconds.
     @counting must be an integer 1 or -1 and is used to tell the clock to
     count up (1) or down (-1). You should make sure the @start has a suitable
     format to count up or down otherwise you could have negative values.
     @end is the end time in a string, format is the same as @start.
     @text is a string to be displayed together with the clock.
     @textpos can be 1 to 4 to set the position of the text related to the
     clock. 1 is on top, 2 right, 3 bottom, 4 left.
     @alarm is called when the end time is reached, should be a callable function.
     It defaults to None.
     The rest will be obvious.
     
     This class implements the Timer.Timer object so you should make sure
     you don't leave threads running in case of a exception."""
     self.logger = logging.getLogger("childsplay.Timer.Clock")
     self.__csurf = char2surf(start, clocksize, clockcolor)
     SPSprite.__init__(self, self.__csurf)
     
     self.__tsprite = MySprite(char2surf(text, textsize, textcolor))
     
     # convert textpos into a xy coordinate
     if textpos == 1:
         x = clockpos[0]
         y = clockpos[1] - textsize
     elif textpos == 3:
         x = clockpos[0]
         y = clockpos + clocksize
     elif textpos == 2:
         x = clockpos[0] + self.__csurf.get_width()
         y = clockpos[1] + \
             ((self.__csurf.get_height() / 2) - (self.__tsprite.get_sprite_height() / 2))
     elif textpos == 4:
         x = clockpos[0] - self.__tsprite.get_sprite_width() 
         y = clockpos[1] + \
             ((self.__csurf.get_height() / 2) - (self.__tsprite.get_sprite_height() / 2))
     self.__tpos = (x, y)
     m, s = start.split(':')
     self.__startminutes, self.__startseconds = int(m), int(s)
     self.__start = start
     m, s = end.split(':')
     self.__endminutes, self.__endseconds = int(m), int(s)
     self.__minutes = self.__startminutes
     self.__seconds = self.__startseconds
     self.__end = end
     self.__count = counting
     self.__csize = clocksize
     self.__cpos = clockpos
     self.__ccol = clockcolor
     self.__text = text
     self.__tsize = textsize
     self.__tcol = textcolor
     self.__alarm = alarm
     self.__clock_stopped = 0
     self.__clock = Timer(1, self.__update, loop=-1, lock=lock)
示例#41
0
 def set_number(self, i, fs):
     s = utils.char2surf(str(i), fsize=fs, fcol=WHITE)
     sr = s.get_rect()
     sr.center = self.rect.center
     self.closedimage.blit(s, sr.topleft)
示例#42
0
 def _remove_prompt(self):
     self.image.blit(self.orgimage, (0, 0))
     self.messagesurf = utils.char2surf(self.message, self.fsize, self.fgcol, bold=self.bold)
     self.image.blit(self.messagesurf, (self.xpadding, self.ypadding))
     self.display_sprite()
示例#43
0
 def __init__(self, data, level, headertext='', norm=None):
     """@data must be a list with tuples (score,date).
     @norm is a tuple containing the mu and sigma value.
     """   
     # dates are stored like this: 07-09-09_10:44:27
     # the data list is a list with tuples like (mu,sigma,date)
     self.logger = logging.getLogger("childsplay.SPWidgets_lgpl.Graph")
     # main surf is 500x300 the graph is a surf of 470x270.
     # 20 for the text bottom and left and 10 for a top and right offset
     gs = pygame.Surface((470, 270))# surf for the graph
     gs.fill((230, 230, 230))
     self.s = pygame.Surface((500, 400))# main surf
     self.s.fill((200, 200, 200))
     if not data:
         self.logger.warning("No data received to show in graph")
         ts = utils.char2surf(_("No data available for this level"), TTFSIZE + 8, ttf=TTF, split=35)
         y = 100
         for s in ts:
             self.s.blit(s, (20, y))
             y += s.get_height()
         Widget.__init__(self, self.s)
         return
     # border around the surf
     pygame.draw.rect(self.s, (100, 100, 100), self.s.get_rect().inflate(-1, -1), 2)
     
     # draw mu line and sigma deviation as a transparent box.
     if norm:
         mu, sigma = norm
         # line
         pygame.draw.line(gs, DARK_BLUE, (0, 270-mu * 27), (470, 270-mu * 27), 3)
         # deviation box, transparent blue
         top_y = mu + (mu / 100.0 * 30)
         bottom_y = mu - (mu / 100.0 * 30)
         darken = pygame.Surface((470, int((top_y-bottom_y) * 27)))
         darken.fill(BLUE)
         darken_factor = 64
         darken.set_alpha(darken_factor)
         gs.blit(darken, (0, 270-top_y * 27))
         
     # draw y-axes graph lines, initial y offset is 30 pixels to leave room for text.
     i = 10
     for y in range(0, 270, 27):
         pygame.draw.line(gs, (0, 0, 0), (0, y), (470, y), 1)
         ts = utils.char2surf(str(i), TTFSIZE-2, ttf=TTF, bold=True)
         i -= 1
         self.s.blit(ts, (4, y + 35))
     ts0 = utils.char2surf(headertext, TTFSIZE-2, ttf=TTF, bold=True)
     ts1 = utils.char2surf(_("Percentile scores for level %s") % level, TTFSIZE, ttf=TTF)
     self.s.blit(ts0, (10, 2))
     self.s.blit(ts1, (20, 20))
     
     # Draw x-axes data
     # determine the size of the x graph steps. This depends on the number of data items.
     # as we fill the x axe. Y step is always the same as the y axe values are always 0-10.
     # The maximum is 470 items, one pixel per data item.
     x_step = 470 / len(data)
     dotslist = []
     # draw dots and x-axes lines
     for x in range(0, 471-x_step, x_step):
         pygame.draw.line(gs, (0, 0, 0), (x, 270), (x, 0), 1)
         try:
             item = data.pop(0)
             #print item
             y = int(float(item[1]) * 27)
             #print "y position",y
             date = item[0]
             #print "date",date
         except (IndexError, TypeError):
             self.logger.exception("Troubles in the datalist, this shouldn't happen\n I try to continue but expect weird results :-)\n Traceback follows:")
             continue
         else:
             pygame.draw.circle(gs, DARK_BLUE, (x + 4, 270-y + 4), 4, 0)
             dotslist.append((x, 270-y))
             # blit date, rotated 90 degrees clockwise
             ts = utils.char2surf(date, TTFSIZE-5, ttf=TTF)
             # rotate 90 degrees
             v_ts = pygame.transform.rotate(ts, 270)
             self.s.blit(v_ts, (x + 20, 320))
     # connect the dots if there are more then one
     if len(dotslist) > 1:
         pygame.draw.lines(gs, BLUE, 0, dotslist, 2)
     pygame.draw.rect(gs, (0, 0, 0), gs.get_rect().inflate(-1, -1), 2)
     # finally blit the two surfaces
     self.s.blit(gs, (20, 40))
     Widget.__init__(self, self.s)
示例#44
0
    def __init__(self, cmd_options, theme='default', vtkb=None, fullscr=None):
        global ACTIVITYDATADIR
        self.logger = logging.getLogger("childsplay.SPgdm.SPGreeter")
        self.logger.debug("Starting")
        self.cmd_options = cmd_options
        self.__name = ''
        captxt = _("Childsplay_sp login")
        if self.cmd_options.theme != 'default':
            captxt = captxt.replace('Childsplay_sp', self.cmd_options.theme)
        ICONPATH = os.path.join(ACTIVITYDATADIR, 'SPData', 'themes', self.cmd_options.theme)
        DEFAULTICONPATH = os.path.join(ACTIVITYDATADIR, 'SPData', 'themes', 'default')
        self.vtkb = vtkb# is used in the _run_loop
        # setup screen
        size = (800, 600)
        if fullscr:
            self.screen = pygame.display.set_mode(size, FULLSCREEN)
        else:
            self.screen = pygame.display.set_mode(size)
        p = os.path.join(ICONPATH, 'spgdm_back.png')
        if not os.path.exists(p):
            p = os.path.join(DEFAULTICONPATH, 'spgdm_back.png')
        back = load_image(p)
        self.screen.blit(back, (0, 0))
        # get the version image
        vs = "Childsplay_sp version: %s" % Version.version
        if self.cmd_options.theme != 'default':
            vs = vs.replace('Childsplay_sp', self.cmd_options.theme)
        if self.cmd_options.adminmode:
            vs = vs + " (Adminmode)"
        vsurf = char2surf(vs, TTFSIZE-4, (0, 0, 0), ttf=TTF, bold=True, antialias=False)
        self.screen.blit(vsurf, (300, 0))
        
        self.actives = SPInit(self.screen, self.screen.convert())
        
        pygame.display.set_caption(captxt.encode('utf-8'))

        # setup our SP widgets
        label = SPLabel(_("Username:"******"Login")
        but.set_text(t)# we set the fontsize below
        
        but.child.create_style()
        but.child.style["font"]["size"] = TTFSIZE
        but.child.style['bgcolor'][ocwc.STATE_NORMAL] = KOBALT_LIGHT_BLUE
        but.create_style()['bgcolor'][ocwc.STATE_NORMAL] = KOBALT_LIGHT_BLUE
        but.connect_signal(ocwc.SIG_CLICKED, self._login_button_callback, self.entry)
        #but.opacity = 255
        but.topleft = (340, 320)
        # We clear the event queue as we sometimes get an crash with the message
        # error: Event queue full
        # Nothing to be found on Google so I've put a clear before the error
        # was generated.
        pygame.event.clear()
        self.renderer.add_widget(but)
        
        # logout button
        p = os.path.join(ICONPATH, 'spgdm_quit_button.png')
        if not os.path.exists(p):
            p = os.path.join(DEFAULTICONPATH, 'spgdm_quit_button.png')
        but = ocw.ImageButton(p)
        but.create_style()['bgcolor'][ocwc.STATE_NORMAL] = KOBALT_LIGHT_BLUE
        but.connect_signal(ocwc.SIG_CLICKED, self._quit_button_callback, but)
        #but.opacity = 180
        but.topleft = (720, 520)
        self.renderer.add_widget(but)
        
        # info button
        p = os.path.join(ICONPATH, 'spgdm_info_button.png')
        if not os.path.exists(p):
            p = os.path.join(DEFAULTICONPATH, 'spgdm_info_button.png')
        but = ocw.ImageButton(p)
        #but.set_text(_("Quit"))
        #but.child.create_style()["font"]["size"] = 36
        but.create_style()['bgcolor'][ocwc.STATE_NORMAL] = KOBALT_LIGHT_BLUE
        but.connect_signal(ocwc.SIG_CLICKED, self._info_button_callback, but)
        #but.opacity = 180
        but.topleft = (20, 520)
        self.renderer.add_widget(but)
        
        self.clock = pygame.time.Clock()
        self.runloop = True
        
        pygame.display.update()
        # run the virtual keyboard if we have one.
        if self.vtkb:
            self._run_vtkb_loop(self.renderer)
        else:
            # else we run a 'normal' loop.
            self._run_loop()
示例#45
0
    def next_exercise(self, currentletter=None):
        self.logger.debug("next_exercise called with %s" % currentletter)
        self.found_x, self.found_y = self.textright_pos[
            0], self.textright_pos[1] + 75
        if len(self.categories) < 1:
            self.categories = self.wordlisthash.keys()
            random.shuffle(self.categories)
        # Change self.newexercise_counter < 4 into 3 to get three times the same category wit a different letter.
        if not self.currentcategory or self.newexercise_counter < 4:
            self.currentcategory = self.categories.pop()
            self.newexercise_counter = 3

        sequence = []
        for line in self.wordlisthash[self.currentcategory][2:]:
            c = line[1].lower()
            if c not in sequence:
                sequence.append(c)

        random.shuffle(sequence)
        if not currentletter:
            self.currentletter = sequence.pop()
        self.logger.debug("picked first letter %s" % self.currentletter)

        self.screen.blit(self.background, (self.x, self.y))
        self.backgr.blit(self.background, (self.x, self.y))

        self.wc.set_firstletter(self.currentletter)
        self.kb._set_firstletter(self.currentletter, self.wrong_sound)
        wordlist = self.wordlisthash[self.currentcategory][1:]
        self.wc.set_wordlist(wordlist)
        self.kb.show()

        h = 0
        txt = self.wordlisthash[self.currentcategory][:1][0][:-1]
        s = utils.char2surf(txt, fsize=20, fcol=self.fgcol)
        r = self.screen.blit(s, (self.texttop_pos[0], self.texttop_pos[1] + h))
        h += s.get_rect().h
        s = utils.char2surf(self.questiontext, fsize=20, fcol=self.fgcol)
        r = self.screen.blit(s, (self.texttop_pos[0], self.texttop_pos[1] + h))

        ls_pos = (r.topright[0], r.topright[1] - 4)

        s = utils.char2surf(self.foundtext, fsize=20, fcol=self.fgcol)
        self.screen.blit(s, self.textright_pos)
        pygame.display.update()
        #### Start animation, increase or decrease attribute value from pygame.time.wait
        for i in range(4, 32):
            s = utils.char2surf(self.currentletter.upper(),
                                fsize=i,
                                fcol=RED,
                                bold=True)
            r = self.screen.blit(s, ls_pos)
            pygame.display.update(r)
            pygame.time.wait(10)
            pygame.display.update(self.screen.blit(self.backgr, r, r))
        s = utils.char2surf(self.currentletter.upper(),
                            fsize=i,
                            fcol=self.fgcol,
                            bold=True)
        r = self.screen.blit(s, ls_pos)
        pygame.display.update(r)
        ########################################################################
        self.actives.add(self.newquestionbut)
        self.newquestionbut.display_sprite()

        self.wc_x, self.wc_y = self.wc_pos

        pygame.display.update()
示例#46
0
    def __init__(self, cmd_options, theme='default', vtkb=None, fullscr=None):
        global ACTIVITYDATADIR
        self.logger = logging.getLogger("childsplay.SPgdm.SPGreeter")
        self.logger.debug("Starting")
        self.cmd_options = cmd_options
        self.__name = ''
        captxt = _("Childsplay_sp login")
        if self.cmd_options.theme != 'default':
            captxt = captxt.replace('Childsplay_sp', self.cmd_options.theme)
        ICONPATH = os.path.join(ACTIVITYDATADIR, 'SPData', 'themes',
                                self.cmd_options.theme)
        DEFAULTICONPATH = os.path.join(ACTIVITYDATADIR, 'SPData', 'themes',
                                       'default')
        self.vtkb = vtkb  # is used in the _run_loop
        # setup screen
        size = (800, 600)
        if fullscr:
            self.screen = pygame.display.set_mode(size, FULLSCREEN)
        else:
            self.screen = pygame.display.set_mode(size)
        p = os.path.join(ICONPATH, 'spgdm_back.png')
        if not os.path.exists(p):
            p = os.path.join(DEFAULTICONPATH, 'spgdm_back.png')
        back = load_image(p)
        self.screen.blit(back, (0, 0))
        # get the version image
        vs = "Childsplay_sp version: %s" % Version.version
        if self.cmd_options.theme != 'default':
            vs = vs.replace('Childsplay_sp', self.cmd_options.theme)
        if self.cmd_options.adminmode:
            vs = vs + " (Adminmode)"
        vsurf = char2surf(vs,
                          TTFSIZE - 4, (0, 0, 0),
                          ttf=TTF,
                          bold=True,
                          antialias=False)
        self.screen.blit(vsurf, (300, 0))

        self.actives = SPInit(self.screen, self.screen.convert())

        pygame.display.set_caption(captxt.encode('utf-8'))

        # setup our SP widgets
        label = SPLabel(_("Username:"******"Login")
        but.set_text(t)  # we set the fontsize below

        but.child.create_style()
        but.child.style["font"]["size"] = TTFSIZE
        but.child.style['bgcolor'][ocwc.STATE_NORMAL] = KOBALT_LIGHT_BLUE
        but.create_style()['bgcolor'][ocwc.STATE_NORMAL] = KOBALT_LIGHT_BLUE
        but.connect_signal(ocwc.SIG_CLICKED, self._login_button_callback,
                           self.entry)
        #but.opacity = 255
        but.topleft = (340, 320)
        # We clear the event queue as we sometimes get an crash with the message
        # error: Event queue full
        # Nothing to be found on Google so I've put a clear before the error
        # was generated.
        pygame.event.clear()
        self.renderer.add_widget(but)

        # logout button
        p = os.path.join(ICONPATH, 'spgdm_quit_button.png')
        if not os.path.exists(p):
            p = os.path.join(DEFAULTICONPATH, 'spgdm_quit_button.png')
        but = ocw.ImageButton(p)
        but.create_style()['bgcolor'][ocwc.STATE_NORMAL] = KOBALT_LIGHT_BLUE
        but.connect_signal(ocwc.SIG_CLICKED, self._quit_button_callback, but)
        #but.opacity = 180
        but.topleft = (720, 520)
        self.renderer.add_widget(but)

        # info button
        p = os.path.join(ICONPATH, 'spgdm_info_button.png')
        if not os.path.exists(p):
            p = os.path.join(DEFAULTICONPATH, 'spgdm_info_button.png')
        but = ocw.ImageButton(p)
        #but.set_text(_("Quit"))
        #but.child.create_style()["font"]["size"] = 36
        but.create_style()['bgcolor'][ocwc.STATE_NORMAL] = KOBALT_LIGHT_BLUE
        but.connect_signal(ocwc.SIG_CLICKED, self._info_button_callback, but)
        #but.opacity = 180
        but.topleft = (20, 520)
        self.renderer.add_widget(but)

        self.clock = pygame.time.Clock()
        self.runloop = True

        pygame.display.update()
        # run the virtual keyboard if we have one.
        if self.vtkb:
            self._run_vtkb_loop(self.renderer)
        else:
            # else we run a 'normal' loop.
            self._run_loop()
示例#47
0
    def display_results(self):
        txt0 = _("You have finished the daily training module.")
        txt1 = _("Your results are:")
        txt1a = _("Your average results per group are:")
        txt2 = _("Activity:")
        txt3 = _("Score:")
        # positions
        txt0_pos = (10, 4)
        txt1_pos = (10, 30)
        txt2_pos = (10, 66)
        txt3_pos = (300, txt2_pos[1])

        # user screen
        groups = {}
        for name, data in self.actdatahash.items():
            group = data['group']
            score = self.sessionresults_raw[name]
            if not groups.has_key(group):
                groups[group] = (0, 0)
            groups[group] = (groups[group][0] + score, groups[group][1] + 1)

        surf = self.backsquare.convert_alpha()
        s = utils.char2surf(txt0, 20, WHITE)
        surf.blit(s, txt0_pos)
        s = utils.char2surf(txt1a, 20, WHITE)
        surf.blit(s, txt1_pos)
        s = utils.char2surf(txt2, 20, WHITE)
        surf.blit(s, txt2_pos)
        s = utils.char2surf(txt3, 20, WHITE)
        surf.blit(s, txt3_pos)
        y = txt2_pos[1] + 46

        for name, data in groups.items():
            score = data[0] / data[1]
            sk = utils.char2surf(name.capitalize(), 20, WHITE)
            sc = '%4.2f' % score
            if score < 6:
                # always just above 6 :-)
                sc = '%4.2f' % (6 + (random.random() / 3))
            sv = utils.char2surf(sc, 20, WHITE)
            surf.blit(sk, (txt2_pos[0], y))
            surf.blit(sv, (txt3_pos[0], y))
            y += 26

        if self.fortune:
            lang = utils.get_locale_local()[0].split('_')[0]
            orm, session = self.SPG.get_orm('game_languages', 'content')
            query = session.query(orm).filter_by(lang=lang)
            lang = [l.ID for l in query.all()]
            session.flush()
            session.close()
            # Disabled the fortune display until we decided what to do with it.
#            orm, session = self.SPG.get_orm('game_quotes', 'content')
#            query = session.query(orm).filter(orm.language.in_(lang))
#            fortune = random.choice([result.quote for result in query.all()])
#            y = 300
#            for line in textwrap.wrap(fortune, 40):
#                s = utils.char2surf(line, 20, WHITE)
#                surf.blit(s, (40, y))
#                y += s.get_rect().h

        dlg = SPWidgets.Dialog(SPWidgets.Widget(surf),
                               buttons=[_("Details"), _("OK")],
                               title=_('Results'))
        dlg.run()  # this blocks any other events loops
        answer = dlg.get_result()
        dlg.erase_sprite()
        if answer[0] == _("OK"):
            return

        # details screen

        surf = self.backsquare.convert_alpha()
        s = utils.char2surf(txt0, 20, WHITE)
        surf.blit(s, txt0_pos)
        s = utils.char2surf(txt1, 20, WHITE)
        surf.blit(s, txt1_pos)
        s = utils.char2surf(txt2, 20, WHITE)
        surf.blit(s, txt2_pos)
        s = utils.char2surf(txt3, 20, WHITE)
        surf.blit(s, txt3_pos)

        y = txt2_pos[1] + 26
        for k, v in self.sessionresults.items():
            sk = utils.char2surf(k, 20, WHITE)
            sv = utils.char2surf(v, 20, WHITE)
            surf.blit(sk, (txt2_pos[0], y))
            surf.blit(sv, (txt3_pos[0], y))
            y += 46

        self.SPG.tellcore_info_dialog(SPWidgets.Widget(surf))
示例#48
0
 def start(self):
     """Mandatory method."""
 
     img = utils.load_image(os.path.join(self.my_datadir,'4row_red.png'))
     self.spacesize = PILSIZE
     self.RedImg = pygame.transform.smoothscale(img, (self.spacesize, self.spacesize))
     
     img = utils.load_image(os.path.join(self.my_datadir,'4row_black.png'))
     self.BlackImg = pygame.transform.smoothscale(img, (self.spacesize, self.spacesize))
     
     img = utils.load_image(os.path.join(self.my_datadir,'4row_board.png'))
     img = pygame.transform.smoothscale(img, (self.spacesize, self.spacesize))
     self.boardImg = img
     
     self.gameClock = pygame.time.Clock()# tobe removed
     self.draggingToken = False
     self.tokenx, self.tokeny = None, None
     
     row = self.SPG.get_current_user_dbrow()
     user_id = self.SPG.get_current_user_id()
     UserImg = None
     offset = 0
     if user_id > 1:# demo is 1
         p = os.path.join(HOMEDIR, 'braintrainer', 'faces', 'big', '%s.png' % user_id)
         if os.path.exists(p):
             UserImg = utils.aspect_scale(utils.load_image(p), (125,125))
             offset = 12
     if not UserImg:
         st = utils.char2surf(row.first_name, 20, fcol=BLACK)
         sn =  utils.char2surf(row.last_name, 20, fcol=BLACK)
         surf = pygame.Surface((150,80), SRCALPHA, 32)
         surf.blit(st,(8,4))
         surf.blit(sn, (8,30))  
         UserImg = surf
     self.UserImg = SPSpriteUtils.SPSprite(UserImg)
     surf = UserImg.copy()
     pygame.draw.rect(surf, GREEN, UserImg.get_rect(), 10)
     self.TurnImgUser = SPSpriteUtils.SPSprite(surf)
     
     AIimg = utils.load_image(os.path.join(self.my_datadir,'computer.png'))
     self.AIimg = SPSpriteUtils.SPSprite(AIimg)
     surf = AIimg.copy()
     pygame.draw.rect(surf, GREEN, AIimg.get_rect(), 10)
     self.TurnAIimg = SPSpriteUtils.SPSprite(surf)
     
     self.WinnerImg = utils.load_image(os.path.join(self.my_datadir,'winner.png'))
     
     self.numbershash = {}
     for i in range(1, BOARDWIDTH+1):
         self.numbershash[i] = utils.load_image(os.path.join(self.my_datadir,'%s.png' % i))
     
     # sounds
     
     self.winSnd = utils.load_music(os.path.join(self.my_datadir,'won.ogg'))
     self.lossSnd = utils.load_music(os.path.join(self.my_datadir,'loss.ogg'))             
            
     # various constants
     self.FPS = 30 # frames per second to update the screen
     WINDOWWIDTH = 800 # width of the program's window, in pixels
     WINDOWHEIGHT = 600 # height in pixels
     
     self.XMARGIN = int((WINDOWWIDTH - BOARDWIDTH * self.spacesize) / 2) # approx. number of pixels on the left or right side of the board to the edge of the window
     self.YMARGIN = int((WINDOWHEIGHT - BOARDHEIGHT * self.spacesize) / 2 + 80) # approx. number of pixels above or below board
     
     self.REDpos = (self.XMARGIN - self.spacesize * 2, self.YMARGIN + (BOARDHEIGHT - 1) * self.spacesize)
     self.BLACKpos = (self.XMARGIN + BOARDWIDTH * self.spacesize + self.spacesize, self.YMARGIN + (BOARDHEIGHT - 1) * self.spacesize)
     self.UserImgpos = (2 + offset, 380)
     self.UserImg.moveto(self.UserImgpos)
     self.TurnImgUser.moveto(self.UserImgpos)
     self.AIimgpos = (660, 380)
     self.AIimg.moveto(self.AIimgpos)
     self.TurnAIimg.moveto(self.AIimgpos)
     self.winner = 'tie'
     self.difficulty = 1# never more then 2, system will freeze
     self.AreWeDT = False
示例#49
0
    def display_results(self):
        txt0 = _("You have finished the daily training module.")
        txt1 = _("Your results are:")
        txt1a = _("Your average results per group are:")
        txt2 = _("Activity:")
        txt3 = _("Score:")
        # positions
        txt0_pos = (10, 4)
        txt1_pos = (10, 30)
        txt2_pos = (10, 66)
        txt3_pos = (300, txt2_pos[1])
        
        # user screen
        groups = {}
        for name, data in self.actdatahash.items():
            group = data['group']
            score = self.sessionresults_raw[name]
            if not groups.has_key(group):
                groups[group] = (0, 0)
            groups[group] = (groups[group][0] + score, groups[group][1] + 1)  
        
        surf = self.backsquare.convert_alpha()
        s = utils.char2surf(txt0, 20, WHITE)
        surf.blit(s, txt0_pos)
        s = utils.char2surf(txt1a, 20, WHITE)
        surf.blit(s, txt1_pos)
        s = utils.char2surf(txt2, 20, WHITE)
        surf.blit(s, txt2_pos)
        s = utils.char2surf(txt3, 20, WHITE)
        surf.blit(s, txt3_pos)
        y = txt2_pos[1] + 46
        
        for name, data in groups.items():
            score = data[0] / data[1]
            sk = utils.char2surf(name.capitalize(), 20, WHITE) 
            sc = '%4.2f' % score
            if score < 6:
                # always just above 6 :-)
                sc = '%4.2f' % (6 + (random.random()/3))
            sv = utils.char2surf(sc, 20, WHITE)
            surf.blit(sk, (txt2_pos[0], y))
            surf.blit(sv, (txt3_pos[0], y))
            y += 26
        
        if self.fortune:
            lang = utils.get_locale_local()[0].split('_')[0]
            orm, session = self.SPG.get_orm('game_languages', 'content')
            query = session.query(orm).filter_by(lang = lang)
            lang = [l.ID for l in query.all()]
            session.flush()
            session.close()
            # Disabled the fortune display until we decided what to do with it.
#            orm, session = self.SPG.get_orm('game_quotes', 'content')
#            query = session.query(orm).filter(orm.language.in_(lang))
#            fortune = random.choice([result.quote for result in query.all()])
#            y = 300
#            for line in textwrap.wrap(fortune, 40):
#                s = utils.char2surf(line, 20, WHITE)
#                surf.blit(s, (40, y))
#                y += s.get_rect().h
        
        dlg = SPWidgets.Dialog(SPWidgets.Widget(surf),buttons=[_("Details"), _("OK")], title=_('Results'))
        dlg.run() # this blocks any other events loops
        answer = dlg.get_result()
        dlg.erase_sprite()
        if answer[0] == _("OK"):
            return
            
        # details screen
               
        surf = self.backsquare.convert_alpha()
        s = utils.char2surf(txt0, 20, WHITE)
        surf.blit(s, txt0_pos)
        s = utils.char2surf(txt1, 20, WHITE)
        surf.blit(s, txt1_pos)
        s = utils.char2surf(txt2, 20, WHITE)
        surf.blit(s, txt2_pos)
        s = utils.char2surf(txt3, 20, WHITE)
        surf.blit(s, txt3_pos)
        
        y = txt2_pos[1] + 26
        for k, v in self.sessionresults.items():
            sk = utils.char2surf(k, 20, WHITE)
            sv = utils.char2surf(v, 20, WHITE)
            surf.blit(sk, (txt2_pos[0], y))
            surf.blit(sv, (txt3_pos[0], y))
            y += 46
        
        self.SPG.tellcore_info_dialog(SPWidgets.Widget(surf))
示例#50
0
class Activity:
    """  Base class mandatory for any SP activty.
    The activity is started by instancing this class by the core.
    This class must at least provide the following methods.
    start (self) called by the core before calling 'next_level'.
    post_next_level (self) called once by the core after 'next_level' *and* after the 321 count. 
    next_level (self,level) called by the core when the user changes levels.
    loop (self,events) called 40 times a second by the core and should be your 
                      main eventloop.
    get_helptitle (self) must return the title of the game can be localized.
    get_help (self) must return a list of strings describing the activty.
    get_helptip (self) must return a list of strings or an empty list
    get_name (self) must provide the activty name in english, not localized in lowercase.
    stop_timer (self) must stop any timers if any.
  """

    def __init__(self,SPGoodies):
        """SPGoodies is a class object that SP sets up and will contain references
        to objects, callback methods and observers
        TODO: add more explaination"""
        self.logger =  logging.getLogger("childsplay.fishtank.Activity")
        self.logger.info("Activity started")
        self.SPG = SPGoodies
        self.scoredisplay = self.SPG.get_scoredisplay()
        self.theme = self.SPG.get_theme()
        self.screen = self.SPG.get_screen()
        self.screenclip = self.SPG.get_screenclip()
        self.blit_pos = self.screenclip.left, self.screenclip.top
        self.orgscreen = pygame.Surface(self.screenclip.size) # we use this to restore the screen
        self.orgscreen.blit(self.screen, (0, 0), self.screenclip)
        self.backgr = self.SPG.get_background()
        # The location of the activities Data dir
        self.my_datadir = os.path.join(self.SPG.get_libdir_path(),'CPData','FishtankData')
        # Location of the CPData dir which holds some stuff used by multiple activities
        self.CPdatadir = os.path.join(self.SPG.get_libdir_path(),'CPData')
        # Location of the alphabet sounds dir
        self.absdir = self.SPG.get_absdir_path()# alphabet sounds dir
        self.rchash = utils.read_rcfile(os.path.join(self.my_datadir, 'fishtank.rc'))
        self.rchash['theme'] = self.theme
        
        self.sounddir = os.path.join(self.my_datadir,'sounds')
        self.bubimg = utils.load_image(os.path.join(self.my_datadir,'backgrounds',self.theme,'blub0.png'))
        self.bubsnd = utils.load_sound(os.path.join(self.sounddir,'blub0.wav'))
        self.splashsnd = utils.load_sound(os.path.join(self.sounddir,'poolsplash.wav'))
        self.WeAreAquarium = False
        self.aquarium_counter = 0
        
        self.aquarium_music_list = glob.glob(os.path.join(self.sounddir,'*.ogg'))
        # You MUST call SPInit BEFORE using any of the SpriteUtils stuff
        # it returns a reference to the special CPGroup
        self.actives = SPSpriteUtils.SPInit(self.screen,self.backgr)
        self.actives.set_onematch(True)
            
    def clear_screen(self):
        self.screen.set_clip()
        self.screen.blit(self.orgscreen,self.blit_pos)
        self.backgr.blit(self.orgscreen,self.blit_pos)
        pygame.display.update()

    def are_we_in_aquarium_mode(self):
        return self.WeAreAquarium

    def get_moviepath(self):
        movie = os.path.join(self.my_datadir,'help.avi')
        return movie

    def refresh_sprites(self):
        """Mandatory method, called by the core when the screen is used for blitting
        and the possibility exists that your sprites are affected by it."""
        self.actives.redraw()

    def get_helptitle(self):
        """Mandatory method"""
        return _("Fishtank")
    
    def get_name(self):
        """Mandatory method, returnt string must be in lowercase."""
        return "fishtank"
    
    def get_help(self):
        """Mandatory methods"""
        text = [_("The aim of this activity:"),
        _("Try to remove the fish by clicking on them with the mouse."),
        " "]
        return text 
    
    def get_helptip(self):
        """Mandatory method, when no tips available returns an empty list"""
        return []
        
    def get_helptype(self):
        """Mandatory method, you must set an type"""
        # Possible types are: Memory, Math, Puzzle, Keyboardtraining, Mousetraining
        #                     Language, Alphabet, Fun, Miscellaneous
        return _("Fun/Mousetraining")
    
    
    def get_helplevels(self):
        """Mandatory method, must return a string with the number of levels
        in the follwing format:
        _("This level has %s levels") % number-of-levels"""
        return _("This activity has %s levels") % 6

    def stop_timer(self):
        """You *must* provide a method to stop timers if you use them.
        The SPC will call this just in case and cache the exception in case 
        there's no 'stop_timer' method""" 
        try:
            self.timer_f.stop()
        except:
            pass
        try:
            self.timer_b.stop()
        except:
            pass
        try:
            self.aquariumsound.stop()
        except:
            pass
        self.clear_screen()

    def score_observer(self, score):
        self.aquarium_counter = 0
        self.WeAreAquarium = False
        self.aquarium_text.erase_sprite()
        self.actives.remove(self.aquarium_text)
#        if self.aquariumsound:
#            self.aquariumsound.stop()

        snd = utils.load_sound(os.path.join(self.my_datadir,'sounds', 'poolsplash.wav')) 
        snd.play()
        if score < 0:
            score = 1
        self.scoredisplay.increase_score(score + self.level*6)
    
    def start(self):
        """Mandatory method."""
        # here we setup our list with images we use to construct sprites through out the levels.
        rawimagelist = []
        filelist = glob.glob(os.path.join(self.my_datadir,'*.png'))
        filelist.sort()
        for i in range(0,len(filelist),2):
            rawimagelist.append((filelist[i],filelist[i+1]))
        self.imagelist = []
        try:
            for imgfile in rawimagelist:
                self.imagelist.append((utils.load_image(imgfile[0]),\
                                   utils.load_image(imgfile[1])))
        except Exception,info:
            self.logger.exception("Error loading images")
            raise utils.MyError()
        self.logger.debug("constructed %s groups of images" % len(self.imagelist))
        # get some 'blub' sounds
        self.sounds = []
        filelist = glob.glob(os.path.join(self.my_datadir,'*.wav'))
        for path in filelist:
            self.sounds.append(utils.load_sound(path))
        # level_data: one tuple per level six in total.
        # tuple values are: number of fish,x coord,delay,step,timersleep
        # x coord of 0 means both left and right
        # Third level adjust the speed of some of the fish
        # from the third level the speeds are randomized.
        self.level_data = [(20,-90,8,4,4),(20,0,8,4,4),(20,0,8,4,4),(20,890,4,6,4),\
                            (20,0,4,8,4),(20,0,4,6,4)]

        surf = utils.char2surf("Aquarium mode", 14, fcol=GREEN)
        self.aquarium_text = SPSpriteUtils.MySprite(surf, pos=(30, 580))
        self.aquarium_text.set_use_current_background()
示例#51
0
    #    f.close()
    wordlist = []
    wc = WordCompleter(wordlist)
    print wc.get_answers('aa')

    import pygame
    from pygame.constants import *
    pygame.init()

    from SPSpriteUtils import SPInit

    scr = pygame.display.set_mode((800, 600))
    scr.fill((135, 206, 250))

    back = scr.convert()
    s = utils.char2surf("Hit ESC to cycle trough the layouts, F1 to quit", 24)
    scr.blit(s, (20, 10))

    actives = SPInit(scr, back)

    pygame.display.flip()

    SPWidgets.Init('braintrainer')

    def cbf(parent, data):
        print "cbf called with: ", parent, data

    kb = None
    for layout in ('qwerty', 'qwerty_square', 'numbers', 'abc', 'abc_square'):
        if kb:
            kb.hide()