[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] getting what an user has written



> Hello. I use this script in a class to get the string what user had written:
> string.string=u""
> strfont=pygame.font.Font(None,16)
> for udalost in pygame.event.get():
>           if udalost.type == KEYDOWN:
>             if udalost.key == K_RETURN: exit=1
>             elif udalost.key == K_BACKSPACE:
>               self.string=self.string[:-1]
>               text=strfont.render(self.string,0,(0,0,0))
>             elif not strfont.size(self.string+udalost.unicode)[0]>mw-8:
>               self.string+=udalost.unicode
>               text=strfont.render(self.string,0,(0,0,0))

 Well ... I wrote this, but surely is not the right way to do it,
because I started working with python+pygame 2-3 weeks ago:


   # Loop to get keystrokes and insert them into the string
   done = 0
   mystring = ""
   while not done:
      clock.tick(20)

      text = font.render( str(mystring) + "_", 1, (180,180,0))
      newsize = text.get_rect()
      screen.fill( bg, [tx+textsize.w, ty, w-textsize.w-32, newsize.h+2] )
      screen.blit( text, (tx+textsize.w, ty) )

      pygame.display.flip()
      for event in pygame.event.get():

         if event.type == KEYDOWN:
            key = event.key

            if key == K_ESCAPE: done = 1

            # Delete key
            elif key == K_BACKSPACE and mystring != []:
               mystring = mystring[:-1]

            # Enter: check if the string is valid
            elif key == K_RETURN and mystring != [] :
                  value, done = mystring, 1

            # Any other key: numbers, letters...
            else:
               the_key = event.unicode
               ascii = ""
               if the_key.isalnum() \
                  or the_key in ( '.', '_', '-', ' ' ):
                     ascii = the_key.encode('latin1')
               if len(mystring) < string_limit and ascii != "":
                  mystring = mystring[:] + ascii


 Hope that helps.

-- 
Santiago Romero (NoP/Compiler)
KUbuntu GNU/Linux
http://www.sromero.org