Partage
  • Partager sur Facebook
  • Partager sur Twitter

[SDL][C++] Classe pour saisie de texte

une classe pour la saisie du texte

    18 août 2006 à 15:00:25

    Bonjour,
    Je viens de réaliser une classe permettant de saisir du texte dans une fenêtre SDL.
    Je laisse les sources ici pour ceux qui sont interressés.
    Si vous avez des propositions pour l'améliorer, ou corriger certains bug, n'hésitez pas !
    J'espère que ça servira quelques personnes !

    Code du header : inputsdl.h :

    /***************************************************************************
     *                     *
     *                                                *
     *                                                                         *
     *   This program is free software; you can redistribute it and/or modify  *
     *   it under the terms of the GNU General Public License as published by  *
     *   the Free Software Foundation; either version 2 of the License, or     *
     *   (at your option) any later version.                                   *
     *                                                                         *
     *   This program is distributed in the hope that it will be useful,       *
     *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
     *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
     *   GNU General Public License for more details.                          *
     *                                                                         *
     *   You should have received a copy of the GNU General Public License     *
     *   along with this program; if not, write to the                         *
     *   Free Software Foundation, Inc.,                                       *
     *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
     ***************************************************************************/







    #ifndef TEXTE
    #define TEXTE



    #include <string>     // inclut les fichers requis pour la création de la classe
    #include <SDL.h>
    #include <SDL_ttf.h>
    #include <SDL_image.h>
    #include <cstdlib>
    #define POLICE "URWChanceryL-MediItal.ttf"
    #define TAILLE 15
    #define COLORBASE 255
    #define MAXSIZE 15


    /*Classe qui gère l'affichage du texte*/


    class cTexte
    {
    protected:

      static int nObjetsTexte;
      static void fInit(); // Initialisation TTF
      static void fQuit(); // Fermeture TTF
      //La chaine de stockage
      std::string chaine;

      //La surface texte
      SDL_Surface *texte;

      SDL_Color textColor; // couleur du texte

      SDL_Rect position; // position du texte (coin supérieur gauche)

      TTF_Font *font; // fonte à utiliser

    public:

      //Constructeur
      cTexte(std::string fonte,std::string text, int taille,int x,int y, int r, int g, int b); // Constructeur max options
      cTexte (std::string text,int x,int y,int taille); // Constructeur rapide


      //Destructeur
      virtual ~cTexte();

      /*Fonctions : */
      //blitte la surface texte
      virtual void fblit(SDL_Surface *ecran);

      //affecte le surface texte finie à une autre surface, qui sera sauvegardée pour l'affichage
      virtual void retourSurface (SDL_Surface *retour, SDL_Rect *pos);



    };


    /*Classe qui gère la saisie de texte par le joueur*/

    class cTexteSaisie : public cTexte
    {
    public :
      // Constructeur
      cTexteSaisie(std::string fonte, int taille,int x,int y, int r, int g, int b,int maxSize,SDL_Surface *fond); // Constructeur max options
      cTexteSaisie(int taille,int x, int y,SDL_Surface *fond); // Constructeur rapide

      // Destructeur

      virtual ~cTexteSaisie();


      /*Fonctions :*/

      virtual void retourSurface (SDL_Surface *retour, SDL_Rect *pos); // Renvoie la Surface

      std::string retourTexte (); // renvoie le texte saisi

      virtual void fblit (SDL_Surface *ecran); // Blitte la surface

      void fSaisie (SDL_Surface *ecran) ; // Fonction qui s'occupe de la saisie

    protected :

      static int nObjetsSaisie;
      static void fInitUnicode(); // Ouverture Unicode
      static void fQuitUnicode(); // Fermeture Unicode
      SDL_Surface *background; // Surface de fond du texte
      int max; // Taille maximum de la chaine
    };


    #endif


    code du .cpp : inputsdl.cpp :
    /***************************************************************************
     *                        *
     *                                                                         *
     *                                                                         *
     *   This program is free software; you can redistribute it and/or modify  *
     *   it under the terms of the GNU General Public License as published by  *
     *   the Free Software Foundation; either version 2 of the License, or     *
     *   (at your option) any later version.                                   *
     *                                                                         *
     *   This program is distributed in the hope that it will be useful,       *
     *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
     *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
     *   GNU General Public License for more details.                          *
     *                                                                         *
     *   You should have received a copy of the GNU General Public License     *
     *   along with this program; if not, write to the                         *
     *   Free Software Foundation, Inc.,                                       *
     *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
     ***************************************************************************/





    #include <string>     // inclut les fichers requis pour la création de la classe
    #include <SDL.h>
    #include <SDL_ttf.h>
    #include <SDL_image.h>
    #include <cstdlib>
    #include "inputsdl.h"


    /*Memebres statiques*/

    int cTexte::nObjetsTexte = 0;

    void cTexte::fInit() // Initialisation de TTF
    {
      if (nObjetsTexte == 0)
      {
        TTF_Init(); /* <---Prévoir gestion des erreurs ici*/
      }
      else
      {}
      return;
    }

    void cTexte::fQuit() // Fermeture de TTF
    {
      if (nObjetsTexte==0)
      {
        TTF_Quit();
      }
      return;
    }

    /*********************CONSTRUCTEURS***********************/

    /*Constructeur élaboré - toutes options*/

    cTexte::cTexte (std::string fonte, std::string text,int taille,int x,int y, int r, int g, int b)
    {
      fInit(); // Vérification du chargement de TTF


      texte=NULL;

      font= TTF_OpenFont(fonte.c_str(),taille); // affectation de la fonte : de nom fonte et de taille taille

      textColor.r=r; //Couleur
      textColor.g=g;
      textColor.b=b;

      position.x=x;  // la position
      position.y=y;

      chaine=text;

      nObjetsTexte++ ;// On a créé un nouvel objet, il est comptabilisé

    }

    /*Constructeur "rapide" - texte + position + taille */

    cTexte::cTexte (std::string text,int x,int y, int taille)
    {
      fInit(); // vérification du chargement de TTF
      texte=NULL;
      font=TTF_OpenFont(POLICE,taille); // Affectation de la fonte : de la POLICE et de la taille

      textColor.r=COLORBASE; // Couleur
      textColor.g=COLORBASE;
      textColor.b=COLORBASE;

      position.x=x; // la position
      position.y=y;

      chaine=text;

      nObjetsTexte++; // On a créé un nouvel objet, il est comptabilisé

    }


    /***********************************************************************************************/


    /***************Destructeur**********************/

    cTexte::~cTexte()
    {
      SDL_FreeSurface(texte); // libère la surface
      TTF_CloseFont(font); // Ferme la police
      nObjetsTexte--; // enlève l'objet de la liste
      fQuit(); // Regarde si on ferme la librairie TTF
    }

    /************************************************/


    /***************************Fonctions*******************/

    void cTexte::fblit (SDL_Surface *ecran)  // Fonction de blit
    {
      texte=TTF_RenderText_Blended(font,chaine.c_str(),textColor);
      SDL_BlitSurface (texte,NULL,ecran,&position);
      return;
    }

    void cTexte::retourSurface (SDL_Surface *retour,SDL_Rect *pos) // conservation de la surface
    {
      retour=NULL// surface de retour= pointeur null
      retour=TTF_RenderText_Blended(font,chaine.c_str(),textColor); // affectation de la surface en la recréant
      pos->x=position.x; //position affectée x
      pos->y=position.y; // position affectée y

      return ;
    }





    /****************************************************************/

    /***************************************************************/

    /***************Sous - Classe : Classe de saisie de Texte****************/

    /*****Membres Statiques****/

    int cTexteSaisie::nObjetsSaisie=0;

    void cTexteSaisie::fInitUnicode()
    {
      if(nObjetsSaisie==0)
      {
        SDL_EnableUNICODE( SDL_ENABLE );
      }
      return;
    }

    void cTexteSaisie::fQuitUnicode()
    {
      if(nObjetsSaisie==0)
      {
        SDL_EnableUNICODE( SDL_DISABLE );
      }
      return;
    }

    /*****Constructeurs *****/

    cTexteSaisie::cTexteSaisie(std::string fonte, int taille,int x,int y, int r, int g, int b,int maxSize,SDL_Surface *fond):cTexte(fonte,"",taille,x,y,r,g,b)
    {

      fInitUnicode();

      background=fond;
      background->refcount++;

      max=maxSize;
      cTexteSaisie::nObjetsSaisie++;
    }


    cTexteSaisie::cTexteSaisie(int taille,int x, int y,SDL_Surface *fond):cTexte("",x,y,taille)
    {
      fInitUnicode();
      background=fond;
      background->refcount++;
      max=MAXSIZE;
      nObjetsSaisie++;
    }
    /**************************/

    void cTexteSaisie::fSaisie(SDL_Surface *ecran) // Fonction de la saisie
    {
      SDL_BlitSurface(background,NULL,ecran,&position);
      SDL_Flip (ecran);
      SDL_Event event; // évènement

      int continuer=1;

      while(continuer)
      {

        SDL_WaitEvent (&event);

        if( event.type == SDL_KEYDOWN )
        {
          //copie de la version actuelle de la chaîne
          std::string temp = chaine;


          //Si la chaîne a une taille inférieure à la taille maximale
          if (chaine.length() < max )
          {
            //Si espace
            if( event.key.keysym.unicode == (Uint16)' ' )
            {
              //ajoutte espace
              chaine += (char)event.key.keysym.unicode;
            }
            //Si nombre
            else if( ( event.key.keysym.unicode >= (Uint16)'0' ) && ( event.key.keysym.unicode <= (Uint16)'9' ) )
            {
              //Ajoutte le nombre
              chaine += (char)event.key.keysym.unicode;
            }
            //Majuscule
            else if( ( event.key.keysym.unicode >= (Uint16)'A' ) && ( event.key.keysym.unicode <= (Uint16)'Z' ) )
            {

              chaine += (char)event.key.keysym.unicode;
            }
            //Minuscule
            else if( ( event.key.keysym.unicode >= (Uint16)'a' ) && ( event.key.keysym.unicode <= (Uint16)'z' ) )
            {

              chaine += (char)event.key.keysym.unicode;
            }
          }

          //cas d'un effacement
          if( ( event.key.keysym.sym == SDLK_BACKSPACE ) && ( chaine.length() != 0 ) )
          {
            //Enlève le dernier caractère
            chaine.erase( chaine.length() - 1 );

          }


          //Si la chaine est différente...
          if( chaine != temp )
          {
            //...on libère la surface
            SDL_FreeSurface( texte );
            fblit (ecran); // on blite

          }


          //Cas de la touche "entré"
          if( ( event.key.keysym.sym == SDLK_RETURN ) && ( chaine.length() != 0 ) )
          {
            continuer = 0;
          }
          SDL_Flip (ecran); // On met à jour l'affichage
        }

      }

      return;
    }

    void cTexteSaisie::fblit (SDL_Surface *ecran)
    {
      texte=TTF_RenderText_Solid(font,chaine.c_str(),textColor);
      SDL_BlitSurface(background,NULL,ecran,&position);
      SDL_BlitSurface (texte,NULL,ecran,&position);


      return ;
    }

    void cTexteSaisie::retourSurface (SDL_Surface *retour, SDL_Rect *pos) //renvoie la surface et la position -> pas très utile pour la saisie
    {

      retour=NULL// surface de retour= pointeur null
      retour=TTF_RenderText_Solid(font,chaine.c_str(),textColor); // affectation de la surface en la recréant
      pos->x=position.x; //position affectée x
      pos->y=position.y; // position affectée y
    }
    /*********************************************************/
    /***********Destructeur**************************/


    cTexteSaisie::~ cTexteSaisie()
    {
      SDL_FreeSurface (background); // libère la surface de fond
      nObjetsSaisie--; // destruction comptabilisée
      fQuitUnicode(); // Regarde si on doit fermer l'unicode
      SDL_FreeSurface(texte); // libère la surface
      TTF_CloseFont(font); // Ferme la police
      nObjetsTexte--; // enlève l'objet de la liste
      fQuit(); // Regarde si on ferme la librairie TTF

    }

    /**************************************************/
    • Partager sur Facebook
    • Partager sur Twitter

    [SDL][C++] Classe pour saisie de texte

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown