IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C++ Discussion :

Morpion avec IA


Sujet :

C++

  1. #1
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 30
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Finance

    Informations forums :
    Inscription : Octobre 2014
    Messages : 16
    Points : 0
    Points
    0
    Par défaut Morpion avec IA
    Bonjour,

    Je suis actuellement en master1 de mathématiques et je dois coder un morpion en C++, un joueur contre l'ordinateur. La consigne est que le joueur ne doit jamais gagner, au mieux il fait un match nul... Après des heures passées sur le sujet j'ai réussi à coder un programme, mais malheureusement quand j’exécute, l'ordinateur joue deux fois et l'utilisateur également, et après ça me renvoie une erreur... Après des heures (et oui encore) à essayer de résoudre le problème, j'en suis toujours au même point...
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    #include <cstdlib>
    #include <cstdio>
    #include <cassert>
     
    #define CROIX  1
    #define ROND   2
     
    //l'ordi joue les X
     
    const int longueur = 5 ;
    const int hauteur = 5 ;
    int nbpions = 0 ;
     
    bool pas_gagne(char *morpion, char c) {
        return 
        (morpion[0] !=c || morpion[2] !=c || morpion[4] !=c) && (morpion[10]!=c || morpion[12]!=c || morpion[14]!=c) && 
        (morpion[20]!=c || morpion[22]!=c || morpion[24]!=c) && (morpion[0] !=c || morpion[10]!=c || morpion[20]!=c) && 
        (morpion[2] !=c || morpion[12]!=c || morpion[22]!=c) && (morpion[4] !=c || morpion[14]!=c || morpion[24]!=c) && 
        (morpion[0] !=c || morpion[12]!=c || morpion[24]!=c) && (morpion[4] !=c || morpion[12]!=c || morpion[20]!=c);
    }
     
    void afficher_morpion(char* morpion) {
        for (int y=0 ; y<hauteur ; y++) {
            for (int x=0 ; x<longueur ; x++) {
                printf("%c", morpion[x+y*longueur]);
            }            
            printf("\n") ;
        }
    }
     
    void jouer(char *morpion, char symb, int a, int b) {
         int coord = a*10 + b*2 ;
         assert (morpion[coord] == ' ') ;
         morpion [coord] = symb ;
         nbpions = nbpions + 1 ;
    }
     
    void dejouer(char *morpion, char symb, int a, int b) {
         int coord = a*10 + b*2 ;
         assert (morpion[coord] == symb) ;
         morpion[coord] = ' ' ;
         nbpions = nbpions - 1 ;
    }
     
    int minimax(char *morpion, char symb, int *meilleura, int *meilleurb) {
      int eval ; //ce qu'on va renvoyer : 0 si match nul, 1 si ordi gagne et -1 si joueur gagne
      int evalencours ;
      int meilleura2 ; 
      int meilleurb2 ;
      char jeu[longueur*hauteur] ;
      for (int i=0 ; i<5 ; i++) {
          jeu[i]= morpion[i] ;
      }
     
      if (nbpions == 9) {
        return 0 ;	// match nul
      }		
     
      if (symb == 'O') {
        // on cherche tous les coups pour le joueur ('O') et on renvoie le minimum des evaluations 
        eval = 100 ;
        for (int i=0 ; i<2 ; i++) {
            for (int j=0 ; j<2 ; j++) {
    	        if (jeu[i*10+j*2] == ' ') {
    	           jouer(jeu, 'O', i, j);
                   if (!pas_gagne(jeu,'O')) {
                      *meilleura = i ; 
                      *meilleurb = j ;
    	              eval = -1 ; // le joueur gagne
    	           } else {
                      evalencours = minimax(jeu, 'X', &meilleura2, &meilleurb2);
    	              if (evalencours < eval) {
    	                  *meilleura = i ; 
                          *meilleurb = j ;
    	                  eval = evalencours ;
    	              }
    	           }
    	        dejouer(jeu, 'O', i, j) ;
    	        }
            }
        }
        return eval;
      } else {
        // on cherche tous les coups pour l'ordi ('X') et on renvoie le maximum des évaluations
        eval = -100 ;
        for (int i=0; i<2 ; i++) { 
            for (int j=0 ; j<2 ; j++) {
            	if (jeu[i*10+j*2] == ' ') {
    	           jouer(jeu, 'X', i, j) ;
    	           if (!pas_gagne(jeu,'X')) {
    	              *meilleura = i ;
                      *meilleurb = j ;
    	              eval = 1 ; // l'ordi gagne
    	           } else {
    	              evalencours = minimax(jeu,'O', &meilleura2, &meilleurb2);
    	              if (evalencours > eval) {
    		             *meilleura = i ; 
                         *meilleurb = j;
                	     eval = evalencours ;
    	              }
                   }
    	           dejouer(jeu, 'X', i, j);
                }
             }
    	}
        return eval;
      }
    }
     
    void tour_joueur(char *morpion, char nom[]) {
         while (true) {
            printf("%s : donnez les coordonnees que vous voulez jouer :\n", nom) ;
            int a ;
            int b ;        
            scanf("%d %d", &a,&b) ;
            int coord = (a-1)*10+(b-1)*2;
            if (morpion[coord]==' ' && a>0 && a<4 && b>0 && b<4) {
                morpion[coord] = 'O' ;
                break ;
            }
         }
    }
     
    int main() {
     
        char nom [256] ;
        printf("Nom joueur : ") ;
        scanf("%s", nom) ;
        printf("\n") ;
     
        char morpion[]="\
     | | \
    -----\
     | | \
    -----\
     | | " ;
     
        nbpions=0 ;
        int iter=0 ;
        int i=rand() ;
        int meilleura=0 ;
        int meilleurb=0 ;
     
        if(i%2==0) {
              printf("%s commence la partie.\n",nom) ;
        } else {
              printf("L'ordinateur commence la partie.\n") ;
        }
        int eval ;
     
        while ((pas_gagne(morpion, 'X') && pas_gagne(morpion, 'O'))  && iter<9) {
              afficher_morpion(morpion);
     
              if(i%2==0) {
                   tour_joueur(morpion,nom) ;
              } else {
                   // tour de l'ordi
                   eval = minimax(morpion, 'X', &meilleura, &meilleurb) ;
                   jouer(morpion, 'X', meilleura, meilleurb) ;
              } 
     
           iter = iter+1 ;
           i = i+1 ;
        }
     
        afficher_morpion(morpion) ;
     
        if (!pas_gagne(morpion, 'O')) {
            printf("%s est victorieux !\n",nom) ; 
        } else {
           if(!pas_gagne(morpion, 'X')) {
               printf("L'ordinateur est victorieux !\n") ;
           }
           else {
                printf("Match nul !\n") ;
           }
        }
     
        system("pause");
        return 0 ;
    }
    Quelqu'un peut il m'aider SVP ? Merci d'avance !!

  2. #2
    Membre régulier Avatar de Schaublore
    Homme Profil pro
    Manuel
    Inscrit en
    Octobre 2014
    Messages
    61
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Manuel
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Octobre 2014
    Messages : 61
    Points : 93
    Points
    93
    Par défaut l'excercice porte bien sont nom
    Salut,

    Je crois que l'erreur viens de la fonction : scanf("%d %d", &a,&b) ;
    J'ai oublié comment ça fonctionne, mais en gros c'est quand tu tape [<-Enter] scanf ne vide pas le buffer. Du coup lorsque vient le tour du second joureur scanf prend le [<-Enter] et aucun digit n'est scanné et ainssi de suite. Mais peut etre que je me trompe

    Le mieux c'est encore de lire:
    http://xrenault.developpez.com/tutoriels/c/scanf/
    http://faq.cprogramming.com/cgi-bin/...wer=1043372399
    f(x) = y

  3. #3
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 30
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Finance

    Informations forums :
    Inscription : Octobre 2014
    Messages : 16
    Points : 0
    Points
    0
    Par défaut
    Oui j'ai vu sur plusieurs sites que la fonction scanf n'est pas forcément la meilleure, mais là dans mon problème je ne vois pas où elle intervient, puisqu'elle n'a aucun rôle dans le jeu de l'ordinateur, et c'est ca qui ne fonctionne pas correctement Mais ça peut quand même avoir un rapport ?

  4. #4
    Membre éclairé

    Homme Profil pro
    Non disponible
    Inscrit en
    Décembre 2012
    Messages
    478
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Non disponible

    Informations forums :
    Inscription : Décembre 2012
    Messages : 478
    Points : 877
    Points
    877
    Billets dans le blog
    1
    Par défaut
    Bonjour,

    Si l'objectif est de coder en c++, c'est râté
    Ici, c'est du full C.

    Est il possible d'utiliser la bibliothèque standard ( std:: ) ?
    C++11 est-il proscrit ?

  5. #5
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 30
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Finance

    Informations forums :
    Inscription : Octobre 2014
    Messages : 16
    Points : 0
    Points
    0
    Par défaut
    Ah zut Mais le prof a dit qu'on pouvait coder en n'importe quel langage, mais qu'il conseillait C++... Mais quelles sont au juste les différences ? Car c'est vrai que je ne vois pas vraiment la différence entre le langage C et C++... Et on a droit à toutes les bibliothèques !

  6. #6
    Membre éclairé

    Homme Profil pro
    Non disponible
    Inscrit en
    Décembre 2012
    Messages
    478
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Non disponible

    Informations forums :
    Inscription : Décembre 2012
    Messages : 478
    Points : 877
    Points
    877
    Billets dans le blog
    1
    Par défaut
    Pas mal de différences en fait..
    Multi paradigme -> possiblité de programmer en procédurale, objet, générique...
    Bibliothèque standard -> permet d'alleger considérablement la mise en place de tableau, chaine de caratère et plein d'autre.
    ...

    A voir si ça vaut le coup d'apprendre tout ça si c'est juste pour l'exercice demandé.

    Sinon je ne vois pas le
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    #include <time.h>
    srand(time(NULL));
    qui initialise le random.

  7. #7
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 30
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Finance

    Informations forums :
    Inscription : Octobre 2014
    Messages : 16
    Points : 0
    Points
    0
    Par défaut
    Oui exact, j'ai oublié cela ! Merci ! Mais ça n'a rien changé au fait que l'ordinateur ne joue que deux fois (et même qu'une seule fois si je place le rond du joueur 1ère ligne 2ème colonne) J'ai encore essayé de chercher une solution mais en vain

  8. #8
    Membre éclairé

    Homme Profil pro
    Non disponible
    Inscrit en
    Décembre 2012
    Messages
    478
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Non disponible

    Informations forums :
    Inscription : Décembre 2012
    Messages : 478
    Points : 877
    Points
    877
    Billets dans le blog
    1
    Par défaut
    Je n'ai pas la réponse, mais peut être qu'en arrangeant deux/trois choses il sera plus facile de s'y retrouver.

    Le tableau de la grille du morpion doit être de 3 * 3.
    Une fonction dédiée à l'affichage prendra en paramètre cette grille et s'occupera de créer les contours et tout.
    Là c'est compliquer tout le reste pour pas grand chose.

    Redécouper en plusieurs petites fonctions minimax() peut aider à la compréhension, et surtout permet de les tester une à une.

    Eviter les break pour sortir d'une fonction. (tour_joueur())

  9. #9
    Membre régulier Avatar de Schaublore
    Homme Profil pro
    Manuel
    Inscrit en
    Octobre 2014
    Messages
    61
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Manuel
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Octobre 2014
    Messages : 61
    Points : 93
    Points
    93
    Par défaut
    Bonjour les internautes,

    Etudiante_maths_info, j'ai compiler ton prog...

    Tu veux utilise un morpion a 3x3 ou a 5x5 ?

    A toute
    f(x) = y

  10. #10
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 30
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Finance

    Informations forums :
    Inscription : Octobre 2014
    Messages : 16
    Points : 0
    Points
    0
    Par défaut
    Oui je vais changer la grille, c'est vrai que ça simplifiera les notations, et je vais essayer de réécrire la fonction minimax avec d'autres fonctions... En espérant que cela m'aide à identifier le problème :-) En tout cas merci pour votre aide !

  11. #11
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 30
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Finance

    Informations forums :
    Inscription : Octobre 2014
    Messages : 16
    Points : 0
    Points
    0
    Par défaut
    Schaublore, pour le moment j'ai une grille 5x5 mais c'est un morpion avec 9 cases (dans la grille est comptée les contours), mais je vais changer mon code pour pouvoir considérer un tableau de 9 éléments, je ferais apparaitre les bordure dans la fonction afficher_morpion !

  12. #12
    Membre régulier Avatar de Schaublore
    Homme Profil pro
    Manuel
    Inscrit en
    Octobre 2014
    Messages
    61
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Manuel
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Octobre 2014
    Messages : 61
    Points : 93
    Points
    93
    Par défaut Examples C et C++ Sans AI
    Re,

    Etudiante_maths_info je trouve ce code bizard: for (int i=0 ; i<2 ; i++)
    Deplus de temps a autre l'assert plante. Cétait un minimum que de dire mon programme plante avec le message "Assertion faild" cf: "assert (morpion[coord] == ' ') ;" Si en plus t'avais dis c'est quand je tape [4], [5], [6] que ca plante je suis sur que tu aurrai eu quelqu'un qui aurrai trouvé le bug de TON programme.


    J'ai un peu cherché sur le web s'il n'y avais pas déja des Morpion TicTacToe déjà codé en C++. Y'a rien qui m'a vraiment plu, alors je poste ici un example en POO où tu pourra voir la difference entre le C et le C++. (Pour moi, le morpion c'est le joureur et le TicTacToe c'est le jeux)

    Il y a 3 classes majeur:
    Le joureur: Dvz:: Player
    Le jeux: Dvz::Game
    La strategie: Dvz::Strategy

    Code c++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    int main(int argc, char *argv[]) {
     
    	Dvz::Morpion* player1 = new Dvz::Morpion(
    		"Player1",
    		Dvz::TicTacToe::CROSS
    	);
    	Dvz::Morpion* player2 = new Dvz::Morpion(
    		"Player2",
    		Dvz::TicTacToe::ROUND
    	);
     
    	Dvz::TicTacToe* tictactoe = new Dvz::TicTacToe();
    	tictactoe->setPlayer1(player1);
    	tictactoe->setPlayer2(player2);
     
    	int success = tictactoe->run();
     
    	delete tictactoe;
    	delete player1;
    	delete player2;
     
    	return success;
    }

    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    /*
     * TicTacToe.cpp
     *
     *  Created on: 20 oct. 2014
     *      Author: Ludor
     */
     
    /**
     * Programme de  morpion. Le jeu s'arrete qd l'un des joueurs a gagne
     * (ie 3 pions semblables sur une ligne, colonne ou diagonale) ou qd
     * la grille est pleine.
     *   <a href="http://www-sop.inria.fr/oasis/personnel/Carine.Courbis/c/" target="_blank">http://www-sop.inria.fr/oasis/person...ine.Courbis/c/</a>
     */
    #include "TicTacToe.h"
     
    #include <iostream>
    #include <cstdlib>
    #include <cmath>
     
    namespace Dvz {
     
    TicTacToe::Cell::Cell():
    	col(0),
    	row(0),
    	ship(TicTacToe::VOID){
    }
     
    TicTacToe::Cell::Cell(int col, int row):
    	col(col),
    	row(row),
    	ship(TicTacToe::VOID){
    }
     
    TicTacToe::Cell::~Cell() {
    }
     
    bool TicTacToe::Cell::isEmpty(void)const {
    	return this->ship==VOID;
    }
     
    void TicTacToe::Cell::setShip(TicTacToe::Ship ship) {
    	this->ship = ship;
    }
     
    TicTacToe::Ship TicTacToe::Cell::getShip(void) {
    	return this->ship;
    }
     
    std::string TicTacToe::Cell::toString(void) {
    	if (this->ship==ROUND)
    		return "O";
    	if (this->ship==CROSS)
    		return "X";
    	return " ";
    }
     
    TicTacToe::TicTacToe():
    	player1(0),
    	player2(0),
    	currentPlayer(0),
    	shipWinner(VOID) {
    	this->reset();
    }
     
    TicTacToe::~TicTacToe() {
    }
     
    void TicTacToe::reset(void) {
    	for (int row=0; row<3; row++) {
    		for (int col=0; col<3; col++) {
    			this->grid[col][row].setShip(VOID);
    		}
    	}
    }
     
    bool TicTacToe::action(Player* player, TicTacToe::Cell cell) {
     
    	if(cell.isEmpty())
    		return false;
     
    	TicTacToe::Ship ship = cell.getShip();
    	if(TicTacToe::VOID==ship)
    		return false;
     
    	if (! this->grid[cell.col][cell.row].isEmpty()) {
    		return false;
    	}
     
    	this->grid[cell.col][cell.row].setShip(ship);
     
    	return true;
    }
     
    std::string TicTacToe::toString(void) {
    	std::string string = "";
    	string.append("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    	string.append("###############################################################################\n");
    	string.append("#                                                                             #\n");
    	string.append("#                                 Tic-Tac Toe                                 #\n");
    	string.append("#                                 -----------                                 #\n");
    	string.append("#                                                                             #\n");
    	string.append("#                                                      By Ludovic Schaublore  #\n");
    	string.append("###############################################################################\n");
    	string.append("\n");
     
    	std::string indent = "                                 ";
     
    	string.append(indent);
    	string.append("+---+---+---+");
    	for (int row=0; row<3; row++) {
    		string.append("\n");
    		string.append(indent);
    		for (int col=0; col<3; col++) {
    			string.append("|");
    			string.append(" ");
    			string.append(this->grid[col][row].toString());
    			string.append(" ");
    		}
    		string.append("|\n");
    		string.append(indent);
    		string.append("+---+---+---+");
    	}
    	return string;
    }
     
    void TicTacToe::setPlayer1(Player* player) {
    	// TODO: Check if player hasShip
    	// TODO: Check if player2 && player1->ship != player2->ship
    	this->player1 = player;
    }
     
    void TicTacToe::setPlayer2(Player* player) {
    	// TODO: Check if player hasShip
    	// TODO: Check if player1 && player1->ship != player2->ship
    	this->player2 = player;
    }
     
    bool TicTacToe::hasWinner(void) {
     
    	this->shipWinner = VOID;
     
    	// check rows
    	const int row0 = 0;
    	if(this->grid[0][row0].getShip() == this->grid[1][row0].getShip()
    	&& this->grid[1][row0].getShip() == this->grid[2][row0].getShip()
    	&& this->grid[0][row0].getShip()!=VOID) {
    		this->shipWinner = this->grid[0][row0].getShip();
    		return true;
    	}
     
    	const int row1 = 1;
    	if(this->grid[0][row1].getShip() == this->grid[1][row1].getShip()
    	&& this->grid[1][row1].getShip() == this->grid[2][row1].getShip()
    	&& this->grid[0][row1].getShip()!=VOID) {
    		this->shipWinner = this->grid[0][row1].getShip();
    		return true;
    	}
     
    	const int row2 = 2;
    	if(this->grid[0][row2].getShip() == this->grid[1][row2].getShip()
    	&& this->grid[1][row2].getShip() == this->grid[2][row2].getShip()
    	&& this->grid[0][row2].getShip()!=VOID) {
    		this->shipWinner = this->grid[0][row2].getShip();
    		return true;
    	}
     
    	// check columns
    	const int col0 = 0;
    	if(this->grid[col0][0].getShip() == this->grid[col0][1].getShip()
    	&& this->grid[col0][1].getShip() == this->grid[col0][2].getShip()
    	&& this->grid[col0][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[col0][0].getShip();
    		return true;
    	}
     
    	const int col1 = 1;
    	if(this->grid[col1][0].getShip() == this->grid[col1][1].getShip()
    	&& this->grid[col1][1].getShip() == this->grid[col1][2].getShip()
    	&& this->grid[col1][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[col1][0].getShip();
    		return true;
    	}
     
    	const int col2 = 2;
    	if(this->grid[col2][0].getShip() == this->grid[col2][1].getShip()
    	&& this->grid[col2][1].getShip() == this->grid[col2][2].getShip()
    	&& this->grid[col2][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[col2][0].getShip();
    		return true;
    	}
     
    	// check diagonal nort-ouest / sud-est
    	if(this->grid[0][0].getShip() == this->grid[1][1].getShip()
    	&& this->grid[1][1].getShip() == this->grid[2][2].getShip()
    	&& this->grid[0][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[1][1].getShip();
    		return true;
    	}
     
    	// check diagonal north-est / sud-ouest
    	if(this->grid[2][0].getShip() == this->grid[1][1].getShip()
    	&& this->grid[1][1].getShip() == this->grid[0][2].getShip()
    	&& this->grid[2][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[1][1].getShip();
    		return true;
    	}
     
    	return false;
    }
     
    Player* TicTacToe::getWinner(void) {
    	Morpion* player1 = static_cast<Morpion*>(this->player1);
    	Morpion* player2 = static_cast<Morpion*>(this->player2);
    	if(this->shipWinner==player1->getShip())
    		return player1;
    	if(this->shipWinner==player2->getShip())
    		return player2;
     
    	return 0;
    }
     
    bool TicTacToe::isFill(void) {
    	for (int row=0; row<3; row++)
    		for (int col=0; col<3; col++)
    			if (VOID==this->grid[row][col].getShip())
    				return false;
    	return true;
    }
     
    bool TicTacToe::isOver(void) {
    	return this->hasWinner() || this->isFill();
    }
     
    Player* TicTacToe::getCurrentPlayer(void) {
    	if (!this->currentPlayer) {
    		this->currentPlayer = this->player1;
    	}
    	return this->currentPlayer;
    }
     
    void TicTacToe::nextPlayer(void) {
    	if (this->player1 == this->getCurrentPlayer()) {
    		this->currentPlayer = this->player2;
    	} else {
    		this->currentPlayer = this->player1;
    	}
    }
     
    // FIXME: Use a static function and change access of action() by protected
    int TicTacToe::run(void) {
     
    	// check players
    	if (!this->player1 || !this->player2) {
    		// this->setError("No player");
    		return -1;// EXIT_FAIL
    	}
     
    	// run game
    	int i = 0;
    	while (!this->hasWinner() && i<9 /*!this->isOver()*/) {// FIXME isOver: see TicTacToe::run
    		std::cout << this->toString() << std::endl;
    		//std::cout << "Cmd: " << std::endl;
    		//std::cout << "Menu: 1[Rule] | 2[Play] | 3[Quit]" << std::endl;
    		std::cout << "\n\n\n";
     
    		this->getCurrentPlayer()->play(this);
    		this->nextPlayer();
    		i++;
    	}
    	std::cout << this->toString() << std::endl;
    	std::cout << "\n\n";
     
    	// check score
    	if (this->hasWinner()) {
    		Player* winner = this->getWinner();
    		std::cout << "And the winner is : " << winner->getName() << std::endl;
    	} else {
    		std::cout << "The game ended in a draw" << std::endl;
    	}
     
    	return 0;// EXIT_SUCCES
    }
     
     
    Morpion::Morpion(): Player(), ship(TicTacToe::VOID) {
    }
     
    Morpion::Morpion(std::string name, TicTacToe::Ship ship):
    		Player(name),
    		ship(ship)
    {
    }
     
    Morpion::~Morpion() {
    }
     
    bool Morpion::play(void* game) {
    	TicTacToe* tictactoe = static_cast<TicTacToe*>(game);
    	if(!tictactoe)
    		return false;
     
    	int id = 0;
    	int i_try;
    	int max_attempts = 10;
    	std::cout << "Please " << this->name << " enter a Cell ID :" << std::endl;
    	for (i_try=0; i_try<max_attempts; i_try++) {
    		std::cout << ">";
    		std::string entry;
    		std::getline(std::cin, entry);
     
    		id = atoi(entry.c_str());
    		if (!id || id<1 || id>9) {
    			std::cout << "A valid Cell ID is required, but '" << entry << "' is not between 1 and 9" << std::endl;
    		} else {
    			break;
    		}
    	}
    	if (i_try>=max_attempts)
    		return false;
     
    	int data[18] = {
    		0, 2,	1, 2,	2, 2,
    		0, 1,	1, 1,	2, 1,
    		0, 0,	1, 0,	2, 0
    	};
    	int row = data[(id-1)*2+1];
    	int col = data[(id-1)*2];
     
    	TicTacToe::Cell cell(col, row);
    	cell.setShip(this->getShip());
     
    	bool success = tictactoe->action(this, cell);
    	if (!success) {
    		std::cout << "This Cell is already played. Retry" << std::endl;
    		success = this->play(game);
    	}
     
    	return success;
    }
     
    TicTacToe::Ship Morpion::getShip(void) {
    	return this->ship;
    }
     
    void Morpion::setShip(TicTacToe::Ship ship) {
    	this->ship = ship;
    }
     
    } /* namespace Dvz */

    Code c++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    /*
     * TicTacToe.h
     *
     *  Created on: 20 oct. 2014
     *      Author: Ludor
     */
     
    #ifndef TICTACTOE_H_
    #define TICTACTOE_H_
     
    #include <string>
     
    namespace Dvz {
     
    /**
     * class Game
     */
    class Game {
    public:
    	virtual int run(void) = 0;
    };
     
    /**
     * class Player
     */
    class Player {
    public:
    	Player(){};
    	Player(std::string name): name(name){};
    	virtual ~Player(){};
    	std::string getName(void){ return this->name;};
    	virtual bool play(void* game) = 0;
    protected:
    	std::string name;
    };
     
    /**
     * class Strategy
     */
    class Strategy {
    public:
    };
     
    /**
     * class TicTacToe
     */
    class TicTacToe : public Game {
    public:
    	enum Ship {
    		VOID,
    		ROUND,
    		CROSS
    	};
     
    	class Cell {
    	public:
    		Cell();
    		explicit Cell(int col, int row);
    		~Cell();
    		bool isEmpty() const;
    		void setShip(Ship ship);
    		Ship getShip(void);
    		std::string toString(void);
    //	protected:
    		int col;
    		int row;
    		Ship ship;
    	};
     
    	TicTacToe();
    	virtual ~TicTacToe();
    	//void help(Player* player, Cell cell);
    	void setPlayer1(Player* player);
    	void setPlayer2(Player* player);
    	void reset(void);
    	bool action(Player* player, Cell cell);
    	bool hasWinner(void);
    	bool isFill(void);
    	bool isOver(void);
    	Player* getCurrentPlayer(void);
    	void nextPlayer(void);
    	Player* getWinner(void);
     
    	virtual int run(void);
     
    	std::string toString(void);
    protected:
    	Player *player1;
    	Player *player2;
    	Player* currentPlayer;
    	Ship shipWinner;
    	Cell grid[3][3];
    };
     
     
    class Morpion : public Player {
    public:
    	Morpion();
    	Morpion(std::string name, TicTacToe::Ship ship);
    	virtual ~Morpion();
     
    	bool play(void *);
    	void setShip(TicTacToe::Ship ship);
    	TicTacToe::Ship getShip(void);
    protected:
    	TicTacToe::Ship ship;
    };
     
    class TicTacToeStrategy: public Strategy {
    public:
    };
     
    class MorpionAi : public Morpion {
    public:
    	bool play(void *);
     
    protected:
    	Strategy* strategy;
    };
     
     
    } /* namespace Dvz */
     
    #endif /* TICTACTOE_H_ */

    La class Morpion se base sur le PadNumérique du clavier.

    MorpionAi n'a pas été codé , a toi de jouer


    Edit: J'ajoute le meme code en C pour voir la diff.
    Dvz_PlayerAi n'a pas été codé (pour que tu ne puisse pas faire de Copier/Coller) ni le random, a toi de jouer (Montre nous le tien en gardant a l'ésprit que "La solution la plus simple est toujours la moins compliquée"

    Code C : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    /* $ gcc -o main main.c && ./main*/
    #define FALSE 0
    #define TRUE  1
    typedef int   boolean;
     
    #include <stdlib.h> // malloc, free
    #include <stdio.h>  // printf
    #include <string.h> // memset, strcpy, strncpy, strcat
     
    #define GRID_SIZE       3
    #define NAME_MAX_LENGTH 256
    #define NAME_DEFAULT    "<Unknow>"
     
    typedef struct _Dvz_Morpion      Dvz_Morpion;
    typedef enum   _Dvz_Ship_Type    Dvz_Ship_Type;
    typedef struct _Dvz_Player       Dvz_Player;
    typedef struct _Dvz_Player_Class Dvz_Player_Class;
     
    /** ***************************************************************************
     * Declaration Ship
     *************************************************************************** */
    enum _Dvz_Ship_Type {
    	Dvz_Ship_VOID,
    	Dvz_Ship_ROUND,
    	Dvz_Ship_CROSS
    };
     
    /** ***************************************************************************
     * Declaration Morpion
     *************************************************************************** */
    struct _Dvz_Morpion {
    	char          grid[GRID_SIZE][GRID_SIZE];
    	Dvz_Player*   player1;
    	Dvz_Player*   player2;
    	Dvz_Player*   current_player;
    	Dvz_Ship_Type ship_winner;
    	int         move;
    };
     
    Dvz_Morpion* Dvz_Morpion_new         (void);
    void         Dvz_Morpion_init        (Dvz_Morpion* morpion);
    void         Dvz_Morpion_delete      (Dvz_Morpion* morpion);
    boolean      Dvz_Morpion_set_player1 (Dvz_Morpion* morpion, Dvz_Player* player);
    boolean      Dvz_Morpion_set_player2 (Dvz_Morpion* morpion, Dvz_Player* player);
    void         Dvz_Morpion_reset       (Dvz_Morpion* morpion);
    boolean      Dvz_Morpion_has_winner  (Dvz_Morpion* morpion);
    Dvz_Player*  Dvz_Morpion_get_winner  (Dvz_Morpion* morpion);
    int          Dvz_Morpion_get_move    (Dvz_Morpion* morpion);// FIXME: get_num_move ?
    boolean      Dvz_Morpion_is_fill     (Dvz_Morpion* morpion);
    boolean      Dvz_Morpion_is_over     (Dvz_Morpion* morpion);
    void         Dvz_Morpion_next_player (Dvz_Morpion* morpion);
    boolean      Dvz_Morpion_action      (Dvz_Morpion* morpion, Dvz_Player* player);
    boolean      Dvz_Morpion_run         (Dvz_Morpion* morpion);
    char*        Dvz_Morpion_to_string   (Dvz_Morpion* morpion);
     
    /** ***************************************************************************
     * Declaration Player
     *************************************************************************** */
    struct _Dvz_Player {
    	//FIXME
    	///char* name;// dynamic
    	char name[NAME_MAX_LENGTH];/// static
    	int row;
    	int col;
    	Dvz_Ship_Type ship;
    };
    Dvz_Player*  Dvz_Player_new        (char* name, Dvz_Ship_Type ship);
    void         Dvz_Player_init       (Dvz_Player* player, char* name, Dvz_Ship_Type ship);
    void         Dvz_Player_delete     (Dvz_Player* player);
     
    static Dvz_Player_Class* dvz_player_class = NULL;
     
    struct _Dvz_Player_Class {
    	boolean (*play) (Dvz_Player* player, Dvz_Morpion* morpion);
    };
     
    /** ***************************************************************************
     * Object Morpion
     *************************************************************************** */
    Dvz_Morpion* Dvz_Morpion_new(void) {
    	Dvz_Morpion* morpion = (Dvz_Morpion*) malloc(sizeof(Dvz_Morpion));
    	Dvz_Morpion_init(morpion);
    	return morpion;
    }
     
    void Dvz_Morpion_init(Dvz_Morpion* morpion) {
    	// TODO: assert morpion
    	morpion->player1 = NULL;
    	morpion->player2 = NULL;
    	Dvz_Morpion_reset(morpion);
    }
     
    void Dvz_Morpion_delete(Dvz_Morpion* morpion) {
    	// TODO: assert morpion
    	free(morpion);
    }
     
    void Dvz_Morpion_reset(Dvz_Morpion* morpion) {
    	// TODO: assert morpion
    	memset(morpion->grid, Dvz_Ship_VOID, GRID_SIZE*GRID_SIZE);
    	morpion->move           = 0;
    	morpion->current_player = NULL;
    	morpion->ship_winner    = Dvz_Ship_VOID;
     
    }
     
    boolean Dvz_Morpion_set_player1(Dvz_Morpion* morpion, Dvz_Player* player) {
    	// TODO assert morpion && player
    	// TODO assert player2 && player1->ship != player2->ship
    	morpion->player1 = player;
    	return 0;
    }
     
    boolean Dvz_Morpion_set_player2(Dvz_Morpion* morpion, Dvz_Player* player) {
    	// TODO assert morpion && player
    	// TODO assert player1 && player1->ship != player2->ship
    	morpion->player2 = player;
    	return 0;
    }
     
    boolean Dvz_Morpion_has_winner(Dvz_Morpion* morpion) {
    	int i;
    	// TODO assert morpion
     
    	morpion->ship_winner = Dvz_Ship_VOID;
     
    	for(i=0; i<3; i++) {
    		// check all rows
    		if(morpion->grid[0][i] == morpion->grid[1][i]
    		&& morpion->grid[1][i] == morpion->grid[2][i]
    		&& morpion->grid[0][i]!=Dvz_Ship_VOID) {
    			morpion->ship_winner = morpion->grid[1][i];
    			return TRUE;
    		}
    		// check all cols
    		if(morpion->grid[i][0] == morpion->grid[i][1]
    		&& morpion->grid[i][1] == morpion->grid[i][2]
    		&& morpion->grid[i][0]!=Dvz_Ship_VOID) {
    			morpion->ship_winner = morpion->grid[i][1];
    			return TRUE;
    		}
    	}
     
    	// check diagonal north-ouest to sud-est
    	if(morpion->grid[0][0] == morpion->grid[1][1]
    	&& morpion->grid[1][1] == morpion->grid[2][2]
    	&& morpion->grid[0][0]!=Dvz_Ship_VOID) {
    		morpion->ship_winner = morpion->grid[1][1];
    		return TRUE;
    	}
     
    	// check diagonal north-est to sud-ouest
    	if(morpion->grid[2][0] == morpion->grid[1][1]
    	&& morpion->grid[1][1] == morpion->grid[0][2]
    	&& morpion->grid[2][0]!=Dvz_Ship_VOID) {
    		morpion->ship_winner = morpion->grid[1][1];
    		return TRUE;
    	}
     
    	return FALSE;
    }
     
    Dvz_Player* Dvz_Morpion_get_winner(Dvz_Morpion* morpion) {
    	// TODO assert morpion
    	if(morpion->ship_winner==morpion->player1->ship)
    		return morpion->player1;
    	if(morpion->ship_winner==morpion->player2->ship)
    		return morpion->player2;
     
    	return NULL;
    }
     
    int Dvz_Morpion_get_move(Dvz_Morpion* morpion) {
    	// TODO assert morpion
    	int row;
    	int col;
     
    	morpion->move = 0;
    	for (row=0; row<3; row++)
    		for (col=0; col<3; col++)
    			if (Dvz_Ship_VOID!=morpion->grid[row][col])
    				morpion->move++;
    	return morpion->move;
    }
     
    boolean Dvz_Morpion_is_fill(Dvz_Morpion* morpion) {
    	// TODO assert morpion
    	if (morpion->move < GRID_SIZE*GRID_SIZE)
    		return FALSE;
     
    	return TRUE;
    }
     
    boolean Dvz_Morpion_is_over(Dvz_Morpion* morpion) {
    	// TODO assert morpion
    	return Dvz_Morpion_has_winner(morpion) || Dvz_Morpion_is_fill(morpion);
    }
     
    Dvz_Player* Dvz_Morpion_get_current_player(Dvz_Morpion* morpion) {
    	if (!morpion->current_player) {
    		morpion->current_player = morpion->player1;
    	}
    	return morpion->current_player;
    }
     
    void Dvz_Morpion_next_player(Dvz_Morpion* morpion) {
    	if (morpion->player1 == morpion->current_player) {
    		morpion->current_player = morpion->player2;
    	} else {
    		morpion->current_player = morpion->player1;
    	}
    	morpion->move++;
    }
     
    boolean Dvz_Morpion_action(Dvz_Morpion* morpion, Dvz_Player* player) {
    	// TODO: assert morpion && player
     
    	// The case is already used
    	if (morpion->grid[player->col][player->row]!=Dvz_Ship_VOID) {
    		return FALSE;
    	}
     
    	morpion->grid[player->col][player->row] = player->ship;
     
    	return TRUE;
    }
     
    boolean Dvz_Morpion_run(Dvz_Morpion* morpion) {
    	// TODO assert morpion
     
    	// check players
    	if (!morpion->player1 || !morpion->player2) {
    		// add_error("No players");
    		return FALSE;
    	}
     
    	// run game
    	// let end-user start the game in a arbitrary state
    	Dvz_Morpion_get_move(morpion);// FIXME
    	morpion->current_player = morpion->player1;// FIXME
     
    	while (!Dvz_Morpion_is_over(morpion)) {
    		char* string = Dvz_Morpion_to_string(morpion);
     
    		boolean success = Dvz_Player_play(
    			Dvz_Morpion_get_current_player(morpion),
    			morpion
    		);
    		Dvz_Morpion_next_player(morpion);
    	}
    	char* string = Dvz_Morpion_to_string(morpion);
     
    	// check score
    	if (Dvz_Morpion_has_winner(morpion)) {
    		Dvz_Player* winner = Dvz_Morpion_get_winner(morpion);
    		printf("And the winner is : %s\n", winner->name);
    	} else {
    		printf("The game ended in a draw\n");
    	}
     
    	return TRUE;
    }
     
    char* Dvz_Morpion_to_string(Dvz_Morpion* morpion) {
    	int row;
    	int col;
    	char* player1;
    	char* player2;
    	Dvz_Player* player;
    	char* underscore;
    	int length1;
    	int length2;
    	int length;
    	char* grid;
     
    	char *_header = "\
    ###############################################################################\n\
    #                                                                             #\n\
    #                                 Tic-Tac Toe                                 #\n\
    #                                 -----------                                 #\n\
    #                                                                             #\n\
    #                                                      by Ludovic Schaublore  #\n\
    ###############################################################################\n";
     
    	char* _grid = "\
                                       _ | _ | _ \n\
                                      ---+---+---\n\
                                       _ | _ | _ \n\
                                      ---+---+---\n\
                                       _ | _ | _ \n";
     
    	char *_menu = "Menu : Reset[r], Quit[q], Help[h], Play[7|8|9|4|5|6|1|2|3]\n";
     
    	player = Dvz_Morpion_get_winner(morpion);
    	if (player==NULL)
    		player = morpion->current_player;
     
    	length1 = strlen(morpion->player1->name);
    	length2 = strlen(morpion->player2->name);
    	length = strlen(player->name);
     
    	player1    = (char*) malloc(length1+4);
    	player2    = (char*) malloc(length2+4);
    	underscore = (char*) malloc(length+1);
     
    	player1 = strcpy(player1, morpion->player1->name);
    	strcat(player1, " [O]");
     
    	player2 = strcpy(player2, "[X] ");
    	strcat(player2, morpion->player2->name);
     
     
    	memset(underscore, '-', length);
    	underscore[length] = '\n';
     
     
    	grid = (char*) malloc(strlen(_grid));
    	strcpy(grid, _grid);
     
    	int i;
    	/* printf("int help[] = {"); for(i=0; i<strlen(_grid); i++) if(_grid[i]=='_') printf("%d, ", i); printf("}\n"); exit(-1);*/
    	int help[] = {35, 39, 43, 127, 131, 135, 219, 223, 227};// index of cell
    	for(row=0; row<3; row++) {
    		for(col=0; col<3; col++){
    			i = (row*3) + col;//linearize coordinate of grid; [0][0]=>0; [2][2]=>9
    			if(morpion->grid[col][row]==Dvz_Ship_VOID)       grid[help[i]] = ' ';
    			else if(morpion->grid[col][row]==Dvz_Ship_ROUND) grid[help[i]] = 'O';
    			else if(morpion->grid[col][row]==Dvz_Ship_CROSS) grid[help[i]] = 'X';
    		}
    	}
     
     
    	printf("%s\n", _header);
     
    	printf("%38s - %s\n", player1, player2);
     
    	if (player == morpion->player1)
    		printf("%35s\n", underscore);
    	else 
    		printf("%51s\n", underscore);
    	printf("\n");
     
    	printf("%s\n\n\n", grid);
     
    	printf("%s\n", _menu);
     
     
    	free(player1);
    	free(player2);
    	free(underscore);
    	free(grid);
     
    	return "";
    }
     
    /** ***************************************************************************
     * Object Player
     *************************************************************************** */
    static boolean Dvz_Player_Class_play(Dvz_Player* player, Dvz_Morpion* morpion) {
    	//TODO: assetr player
    	//TODO: assert morpion
    	char entry[2];
    	boolean success;
    	int i_try;
    	int max_attempts = 10;
    	int id = 0;
    	int data[18] = {
    		0, 2,	1, 2,	2, 2,
    		0, 1,	1, 1,	2, 1,
    		0, 0,	1, 0,	2, 0
    	};
     
    	printf("Please '%s' enter a Cell ID :\n", player->name);
    	for (i_try=0; i_try<max_attempts; i_try++) {
    		printf(">");
    		scanf("%s", entry);// FIXME
     
    		id = atoi(entry);
    		if (!id || id<1 || id>9) {
    			printf("A valid Cell ID is required, but '%s' is not between 1 and 9\n", entry);
    		} else {
    			break;
    		}
    	}
    	if (i_try>=max_attempts)
    		return FALSE;
     
    	/* Numeric Pad conversion to Grid coordinated */
    	player->row = data[(id-1)*2+1];
    	player->col = data[(id-1)*2];
     
    	success = Dvz_Morpion_action(morpion, player);
    	if (!success) {
    		printf("This Cell is already played. Retry\n");
    		success = Dvz_Player_Class_play(player, morpion);
    	}
     
    	return TRUE;
    }
     
    static void Dvz_Type_new(void) {
    	dvz_player_class = (Dvz_Player_Class*) malloc(sizeof(Dvz_Player_Class));
    }
     
    Dvz_Player* Dvz_Player_new(char* name, Dvz_Ship_Type ship) {
    	Dvz_Player* player = (Dvz_Player*) malloc(sizeof(Dvz_Player));
    	Dvz_Player_init(player, name, ship);
     
    	dvz_player_class->play = Dvz_Player_Class_play;
     
    	return player;
    }
     
    void Dvz_Player_init(Dvz_Player* player, char* name, Dvz_Ship_Type ship) {
    	int length;
    	// TODO: assert player
    	// TODO assert ship==Dvz_Ship_ROUND || ship == Dvz_Ship_CROSS
     
    	length = strlen(name);
    	if (!length) {
    		// TODO: add_warning(Name is empty);
    		strcpy(player->name, NAME_DEFAULT);
    	} else if (length<(NAME_MAX_LENGTH-1)) {
    		strcpy(player->name, name);
    	} else {
    		// TODO: add_warning(Name is too long, name was shorten);
    		strncpy(player->name, name, NAME_MAX_LENGTH-1-3);
    		strcat(player->name, "...");
    	}
     
    	player->ship = ship;
    }
     
    void Dvz_Player_delete(Dvz_Player* player) {
    	///if player->name = malloc(length+1);
    	///free(player->name);
    	free(player);
    }
     
    boolean Dvz_Player_play(Dvz_Player* player, Dvz_Morpion* morpion) {
    	//assert player && morpion
    	return dvz_player_class->play(player, morpion);
    }
     
    /** ***************************************************************************
     * entry point
     *************************************************************************** */
    int main(int argc, char *argv[]) {
    	int success;
    	Dvz_Morpion* morpion;
    	Dvz_Player* player1;
    	Dvz_Player* player2;
    	char name1[] = "Emi";
    	char name2[] = "Ludor";
     
    	Dvz_Type_new();
     
    	player1 = Dvz_Player_new(name1, Dvz_Ship_ROUND);
    	player2 = Dvz_Player_new(name2, Dvz_Ship_CROSS);
     
    	morpion = Dvz_Morpion_new();
    	if (!morpion) {
    		// Error can't allocate memory
    		return -1;
    	}
    	Dvz_Morpion_set_player1(morpion, player1);
    	Dvz_Morpion_set_player2(morpion, player2);
     
    	success = Dvz_Morpion_run(morpion);
    	if (success!=TRUE) {
    		printf("\n");
    	}
     
    	Dvz_Player_delete(player1);
    	Dvz_Player_delete(player2);
    	Dvz_Morpion_delete(morpion);
     
    	//Dvz_Type_delete();
    //L'omaga Choco: contre fumer
    // Elixir: fermenté poly
     
    	return success;
    }
    f(x) = y

  13. #13
    Rédacteur/Modérateur


    Homme Profil pro
    Network game programmer
    Inscrit en
    Juin 2010
    Messages
    7 115
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Canada

    Informations professionnelles :
    Activité : Network game programmer

    Informations forums :
    Inscription : Juin 2010
    Messages : 7 115
    Points : 32 967
    Points
    32 967
    Billets dans le blog
    4
    Par défaut
    Tous ces new dans le main sont bien inutiles.

    Btw, le morpion c'est un classique, alors oui ça existe sur le net.
    Mais s'agissant d'un devoir d'école, mieux vaut éviter le copier/coller (après tu fais ce que tu veux avec ta conscience et ton prof).

    A ce stade, et à ton niveau, le mieux serait encore de recommencer de 0 et itérer progressivement. Vouloir tout faire d'une traite est le meilleur moyen d'arriver à ton résultat : rien ne marche, et tu sais pas pourquoi. Et c'est trop mal écrit et bordélique pour que quiconque ait vraiment envie, toi y compris, de le relire.

    La 1° chose à faire c'est d'afficher une grille, après il reste les manipulation de la grille et elles sont fort simples et biens connues pour un morpion : mettre une croix ou un rond dans une case auparavant vide.
    Pensez à consulter la FAQ ou les cours et tutoriels de la section C++.
    Un peu de programmation réseau ?
    Aucune aide via MP ne sera dispensée. Merci d'utiliser les forums prévus à cet effet.

  14. #14
    Expert éminent sénior
    Avatar de koala01
    Homme Profil pro
    aucun
    Inscrit en
    Octobre 2004
    Messages
    11 614
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : Belgique

    Informations professionnelles :
    Activité : aucun

    Informations forums :
    Inscription : Octobre 2004
    Messages : 11 614
    Points : 30 626
    Points
    30 626
    Par défaut
    Salut,
    Citation Envoyé par Schaublore Voir le message
    Re,

    Etudiante_maths_info je trouve ce code bizard: for (int i=0 ; i<2 ; i++)
    Deplus de temps a autre l'assert plante. Cétait un minimum que de dire mon programme plante avec le message "Assertion faild" cf: "assert (morpion[coord] == ' ') ;" Si en plus t'avais dis c'est quand je tape [4], [5], [6] que ca plante je suis sur que tu aurrai eu quelqu'un qui aurrai trouvé le bug de TON programme.


    J'ai un peu cherché sur le web s'il n'y avais pas déja des Morpion TicTacToe déjà codé en C++. Y'a rien qui m'a vraiment plu, alors je poste ici un example en POO où tu pourra voir la difference entre le C et le ++. (Pour moi, le morpion c'est le joureur et le TicTacToe c'est le jeux)

    Il y a 3 classes majeur:
    Le joureur: Dvz:: Player
    Le jeux: Dvz::Game
    La strategie: Dvz::Strategy

    Code c++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    int main(int argc, char *argv[]) {
     
    	Dvz::Morpion* player1 = new Dvz::Morpion(
    		"Player1",
    		Dvz::TicTacToe::CROSS
    	);
    	Dvz::Morpion* player2 = new Dvz::Morpion(
    		"Player2",
    		Dvz::TicTacToe::ROUND
    	);
     
    	Dvz::TicTacToe* tictactoe = new Dvz::TicTacToe();
    	tictactoe->setPlayer1(player1);
    	tictactoe->setPlayer2(player2);
     
    	int success = tictactoe->run();
     
    	delete tictactoe;
    	delete player1;
    	delete player2;
     
    	return success;
    }

    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    /*
     * TicTacToe.cpp
     *
     *  Created on: 20 oct. 2014
     *      Author: Ludor
     */
     
    /**
     * Programme de  morpion. Le jeu s'arrete qd l'un des joueurs a gagne
     * (ie 3 pions semblables sur une ligne, colonne ou diagonale) ou qd
     * la grille est pleine.
     *   <a href="http://www-sop.inria.fr/oasis/personnel/Carine.Courbis/c/" target="_blank">http://www-sop.inria.fr/oasis/person...ine.Courbis/c/</a>
     */
    #include "TicTacToe.h"
     
    #include <iostream>
    #include <cstdlib>
    #include <cmath>
     
    namespace Dvz {
     
    TicTacToe::Cell::Cell():
    	col(0),
    	row(0),
    	ship(TicTacToe::VOID){
    }
     
    TicTacToe::Cell::Cell(int col, int row):
    	col(col),
    	row(row),
    	ship(TicTacToe::VOID){
    }
     
    TicTacToe::Cell::~Cell() {
    }
     
    bool TicTacToe::Cell::isEmpty(void)const {
    	return this->ship==VOID;
    }
     
    void TicTacToe::Cell::setShip(TicTacToe::Ship ship) {
    	this->ship = ship;
    }
     
    TicTacToe::Ship TicTacToe::Cell::getShip(void) {
    	return this->ship;
    }
     
    std::string TicTacToe::Cell::toString(void) {
    	if (this->ship==ROUND)
    		return "O";
    	if (this->ship==CROSS)
    		return "X";
    	return " ";
    }
     
    TicTacToe::TicTacToe():
    	player1(0),
    	player2(0),
    	currentPlayer(0),
    	shipWinner(VOID) {
    	this->reset();
    }
     
    TicTacToe::~TicTacToe() {
    }
     
    void TicTacToe::reset(void) {
    	for (int row=0; row<3; row++) {
    		for (int col=0; col<3; col++) {
    			this->grid[col][row].setShip(VOID);
    		}
    	}
    }
     
    bool TicTacToe::action(Player* player, TicTacToe::Cell cell) {
     
    	if(cell.isEmpty())
    		return false;
     
    	TicTacToe::Ship ship = cell.getShip();
    	if(TicTacToe::VOID==ship)
    		return false;
     
    	if (! this->grid[cell.col][cell.row].isEmpty()) {
    		return false;
    	}
     
    	this->grid[cell.col][cell.row].setShip(ship);
     
    	return true;
    }
     
    std::string TicTacToe::toString(void) {
    	std::string string = "";
    	string.append("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    	string.append("###############################################################################\n");
    	string.append("#                                                                             #\n");
    	string.append("#                                 Tic-Tac Toe                                 #\n");
    	string.append("#                                 -----------                                 #\n");
    	string.append("#                                                                             #\n");
    	string.append("#                                                      By Ludovic Schaublore  #\n");
    	string.append("###############################################################################\n");
    	string.append("\n");
     
    	std::string indent = "                                 ";
     
    	string.append(indent);
    	string.append("+---+---+---+");
    	for (int row=0; row<3; row++) {
    		string.append("\n");
    		string.append(indent);
    		for (int col=0; col<3; col++) {
    			string.append("|");
    			string.append(" ");
    			string.append(this->grid[col][row].toString());
    			string.append(" ");
    		}
    		string.append("|\n");
    		string.append(indent);
    		string.append("+---+---+---+");
    	}
    	return string;
    }
     
    void TicTacToe::setPlayer1(Player* player) {
    	// TODO: Check if player hasShip
    	// TODO: Check if player2 && player1->ship != player2->ship
    	this->player1 = player;
    }
     
    void TicTacToe::setPlayer2(Player* player) {
    	// TODO: Check if player hasShip
    	// TODO: Check if player1 && player1->ship != player2->ship
    	this->player2 = player;
    }
     
    bool TicTacToe::hasWinner(void) {
     
    	this->shipWinner = VOID;
     
    	// check rows
    	const int row0 = 0;
    	if(this->grid[0][row0].getShip() == this->grid[1][row0].getShip()
    	&& this->grid[1][row0].getShip() == this->grid[2][row0].getShip()
    	&& this->grid[0][row0].getShip()!=VOID) {
    		this->shipWinner = this->grid[0][row0].getShip();
    		return true;
    	}
     
    	const int row1 = 1;
    	if(this->grid[0][row1].getShip() == this->grid[1][row1].getShip()
    	&& this->grid[1][row1].getShip() == this->grid[2][row1].getShip()
    	&& this->grid[0][row1].getShip()!=VOID) {
    		this->shipWinner = this->grid[0][row1].getShip();
    		return true;
    	}
     
    	const int row2 = 2;
    	if(this->grid[0][row2].getShip() == this->grid[1][row2].getShip()
    	&& this->grid[1][row2].getShip() == this->grid[2][row2].getShip()
    	&& this->grid[0][row2].getShip()!=VOID) {
    		this->shipWinner = this->grid[0][row2].getShip();
    		return true;
    	}
     
    	// check columns
    	const int col0 = 0;
    	if(this->grid[col0][0].getShip() == this->grid[col0][1].getShip()
    	&& this->grid[col0][1].getShip() == this->grid[col0][2].getShip()
    	&& this->grid[col0][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[col0][0].getShip();
    		return true;
    	}
     
    	const int col1 = 1;
    	if(this->grid[col1][0].getShip() == this->grid[col1][1].getShip()
    	&& this->grid[col1][1].getShip() == this->grid[col1][2].getShip()
    	&& this->grid[col1][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[col1][0].getShip();
    		return true;
    	}
     
    	const int col2 = 2;
    	if(this->grid[col2][0].getShip() == this->grid[col2][1].getShip()
    	&& this->grid[col2][1].getShip() == this->grid[col2][2].getShip()
    	&& this->grid[col2][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[col2][0].getShip();
    		return true;
    	}
     
    	// check diagonal nort-ouest / sud-est
    	if(this->grid[0][0].getShip() == this->grid[1][1].getShip()
    	&& this->grid[1][1].getShip() == this->grid[2][2].getShip()
    	&& this->grid[0][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[1][1].getShip();
    		return true;
    	}
     
    	// check diagonal north-est / sud-ouest
    	if(this->grid[2][0].getShip() == this->grid[1][1].getShip()
    	&& this->grid[1][1].getShip() == this->grid[0][2].getShip()
    	&& this->grid[2][0].getShip()!=VOID) {
    		this->shipWinner = this->grid[1][1].getShip();
    		return true;
    	}
     
    	return false;
    }
     
    Player* TicTacToe::getWinner(void) {
    	Morpion* player1 = static_cast<Morpion*>(this->player1);
    	Morpion* player2 = static_cast<Morpion*>(this->player2);
    	if(this->shipWinner==player1->getShip())
    		return player1;
    	if(this->shipWinner==player2->getShip())
    		return player2;
     
    	return 0;
    }
     
    bool TicTacToe::isFill(void) {
    	for (int row=0; row<3; row++)
    		for (int col=0; col<3; col++)
    			if (VOID==this->grid[row][col].getShip())
    				return false;
    	return true;
    }
     
    bool TicTacToe::isOver(void) {
    	return this->hasWinner() || this->isFill();
    }
     
    Player* TicTacToe::getCurrentPlayer(void) {
    	if (!this->currentPlayer) {
    		this->currentPlayer = this->player1;
    	}
    	return this->currentPlayer;
    }
     
    void TicTacToe::nextPlayer(void) {
    	if (this->player1 == this->getCurrentPlayer()) {
    		this->currentPlayer = this->player2;
    	} else {
    		this->currentPlayer = this->player1;
    	}
    }
     
    // FIXME: Use a static function and change access of action() by protected
    int TicTacToe::run(void) {
     
    	// check players
    	if (!this->player1 || !this->player2) {
    		// this->setError("No player");
    		return -1;// EXIT_FAIL
    	}
     
    	// run game
    	int i = 0;
    	while (!this->hasWinner() && i<9 /*!this->isOver()*/) {// FIXME isOver: see TicTacToe::run
    		std::cout << this->toString() << std::endl;
    		//std::cout << "Cmd: " << std::endl;
    		//std::cout << "Menu: 1[Rule] | 2[Play] | 3[Quit]" << std::endl;
    		std::cout << "\n\n\n";
     
    		this->getCurrentPlayer()->play(this);
    		this->nextPlayer();
    		i++;
    	}
    	std::cout << this->toString() << std::endl;
    	std::cout << "\n\n";
     
    	// check score
    	if (this->hasWinner()) {
    		Player* winner = this->getWinner();
    		std::cout << "And the winner is : " << winner->getName() << std::endl;
    	} else {
    		std::cout << "The game ended in a draw" << std::endl;
    	}
     
    	return 0;// EXIT_SUCCES
    }
     
     
    Morpion::Morpion(): Player(), ship(TicTacToe::VOID) {
    }
     
    Morpion::Morpion(std::string name, TicTacToe::Ship ship):
    		Player(name),
    		ship(ship)
    {
    }
     
    Morpion::~Morpion() {
    }
     
    bool Morpion::play(void* game) {
    	TicTacToe* tictactoe = static_cast<TicTacToe*>(game);
    	if(!tictactoe)
    		return false;
     
    	int id = 0;
    	int i_try;
    	int max_attempts = 10;
    	std::cout << "Please " << this->name << " enter a Cell ID :" << std::endl;
    	for (i_try=0; i_try<max_attempts; i_try++) {
    		std::cout << ">";
    		std::string entry;
    		std::getline(std::cin, entry);
     
    		id = atoi(entry.c_str());
    		if (!id || id<1 || id>9) {
    			std::cout << "A valid Cell ID is required, but '" << entry << "' is not between 1 and 9" << std::endl;
    		} else {
    			break;
    		}
    	}
    	if (i_try>=max_attempts)
    		return false;
     
    	int data[18] = {
    		0, 2,	1, 2,	2, 2,
    		0, 1,	1, 1,	2, 1,
    		0, 0,	1, 0,	2, 0
    	};
    	int row = data[(id-1)*2+1];
    	int col = data[(id-1)*2];
     
    	TicTacToe::Cell cell(col, row);
    	cell.setShip(this->getShip());
     
    	bool success = tictactoe->action(this, cell);
    	if (!success) {
    		std::cout << "This Cell is already played. Retry" << std::endl;
    		success = this->play(game);
    	}
     
    	return success;
    }
     
    TicTacToe::Ship Morpion::getShip(void) {
    	return this->ship;
    }
     
    void Morpion::setShip(TicTacToe::Ship ship) {
    	this->ship = ship;
    }
     
    } /* namespace Dvz */

    Code c++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    /*
     * TicTacToe.h
     *
     *  Created on: 20 oct. 2014
     *      Author: Ludor
     */
     
    #ifndef TICTACTOE_H_
    #define TICTACTOE_H_
     
    #include <string>
     
    namespace Dvz {
     
    /**
     * class Game
     */
    class Game {
    public:
    	virtual int run(void) = 0;
    };
     
    /**
     * class Player
     */
    class Player {
    public:
    	Player(){};
    	Player(std::string name): name(name){};
    	virtual ~Player(){};
    	std::string getName(void){ return this->name;};
    	virtual bool play(void* game) = 0;
    protected:
    	std::string name;
    };
     
    /**
     * class Strategy
     */
    class Strategy {
    public:
    };
     
    /**
     * class TicTacToe
     */
    class TicTacToe : public Game {
    public:
    	enum Ship {
    		VOID,
    		ROUND,
    		CROSS
    	};
     
    	class Cell {
    	public:
    		Cell();
    		explicit Cell(int col, int row);
    		~Cell();
    		bool isEmpty() const;
    		void setShip(Ship ship);
    		Ship getShip(void);
    		std::string toString(void);
    //	protected:
    		int col;
    		int row;
    		Ship ship;
    	};
     
    	TicTacToe();
    	virtual ~TicTacToe();
    	//void help(Player* player, Cell cell);
    	void setPlayer1(Player* player);
    	void setPlayer2(Player* player);
    	void reset(void);
    	bool action(Player* player, Cell cell);
    	bool hasWinner(void);
    	bool isFill(void);
    	bool isOver(void);
    	Player* getCurrentPlayer(void);
    	void nextPlayer(void);
    	Player* getWinner(void);
     
    	virtual int run(void);
     
    	std::string toString(void);
    protected:
    	Player *player1;
    	Player *player2;
    	Player* currentPlayer;
    	Ship shipWinner;
    	Cell grid[3][3];
    };
     
     
    class Morpion : public Player {
    public:
    	Morpion();
    	Morpion(std::string name, TicTacToe::Ship ship);
    	virtual ~Morpion();
     
    	bool play(void *);
    	void setShip(TicTacToe::Ship ship);
    	TicTacToe::Ship getShip(void);
    protected:
    	TicTacToe::Ship ship;
    };
     
    class TicTacToeStrategy: public Strategy {
    public:
    };
     
    class MorpionAi : public Morpion {
    public:
    	bool play(void *);
     
    protected:
    	Strategy* strategy;
    };
     
     
    } /* namespace Dvz */
     
    #endif /* TICTACTOE_H_ */

    La class Morpion se base sur le PadNumérique du clavier.

    MorpionAi n'a pas été codé, a toi de jouer
    J'apprécie, vraiment, ton effort... Mais, honnêtement!!! Brrr ...il fait peur !!!!!

    Beaucoup trop de new (et de delete) d'accesseurs et de mutateurs à mon gout, une fonction virutelle pure dans une classe pour laquelle tu ne définis pas le destructeur qui aurait du, au choix, être protégé et non virtuel ou public et virtuel, des fonctions pour lesquelles la liste de paramètres vide prend un void, une matrice 3*3 qui aurait largement mérité d'être "linéarisée" pour être représentée par un tableau à une seule dimension, utilisation de fonctions issues du C au lieu de préférer les fonctions équivalentes proposées par C++, paramètre de type void *, j'en passe et de meilleures

    Pourtant, il faut avouer qu'il y a de tres bonnes choses (respect stricte du SRP), mais même là, cela fait quelque peu "over-ingeenering" .

    Par exemple, je comprend la raison qui t'a incité à créer une classe de base Game avant de dériver ta classe TicTacToe de cette classe de base (même si Game aurait du du avoir un destructeur virutel public ou protégé et non virtuel et qu'elle aurait du être non copiable et non affectable, vu qu'elle a sémantique d'entité). Mais bon, ce n'est réellement intéressant que si tu commences à envisager de permettre au joueur de choisir le jeu auquel il veut jouer... Intéressant, certes, mais... inutile dans le cas présent... On peut d'ailleurs en dire de même toutes tes classes de bases (Player et Strategy qui, en l'occurrence, ne sert pas à grand chose, même si on comprend que l'idée est de mettre l'IA dedans )

    Heuu... Tu ne viendrais pas du monde de java, quelques fois
    A méditer: La solution la plus simple est toujours la moins compliquée
    Ce qui se conçoit bien s'énonce clairement, et les mots pour le dire vous viennent aisément. Nicolas Boileau
    Compiler Gcc sous windows avec MinGW
    Coder efficacement en C++ : dans les bacs le 17 février 2014
    mon tout nouveau blog

  15. #15
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 30
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Finance

    Informations forums :
    Inscription : Octobre 2014
    Messages : 16
    Points : 0
    Points
    0
    Par défaut
    Oulala je suis complètement perdue... J'ai déjà recommencé plusieurs fois mais toujours le même resultat... J'ai codé un morpion 2 joueurs déjà pour voir comment les bases fonctionnent (affiche d'un morpion, remplissage et conditions d'arrêt) mais ça ne m'a pas aidé pour mieux réussir avec l'intelligence artificielle...

  16. #16
    Membre éclairé

    Homme Profil pro
    Non disponible
    Inscrit en
    Décembre 2012
    Messages
    478
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Non disponible

    Informations forums :
    Inscription : Décembre 2012
    Messages : 478
    Points : 877
    Points
    877
    Billets dans le blog
    1
    Par défaut
    En notant ainsi les étapes, je pense qu'on peut faire le tour des possibilités :

    si joueur commence
    si pion au centre
    placer pion en diagonale
    ...
    si pion en diagonale
    placer pion au centre
    ...
    si pion côté
    placer pion au centre
    ...

    si IA commence
    placer pion au centre
    si pion en diagonale
    placer pion sur autre diagonale
    ...
    si pion côté
    placer pion en diagonale à côté
    ...

  17. #17
    Rédacteur/Modérateur


    Homme Profil pro
    Network game programmer
    Inscrit en
    Juin 2010
    Messages
    7 115
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Canada

    Informations professionnelles :
    Activité : Network game programmer

    Informations forums :
    Inscription : Juin 2010
    Messages : 7 115
    Points : 32 967
    Points
    32 967
    Billets dans le blog
    4
    Par défaut
    honnêtement je serais choqué si un tel projet contenait plus que ces fonctions
    - main (faut bien)
    - placerPion(case, rond/croix)
    - afficherGrille

    une structure un peu sexie pour représenter un plateau de jeu
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    enum Pion { Vide, Rond, Croix };
    struct Plateau { Pion[9] cases; };
    après ça, tu fais une fonction tourIA qui en fonction de l'état de la grille choisit son action
    et emballé c'est pesé

    edit: aller je concède une fonction victoire qui te retourne un bool (ou mieux : un Pion), en binome avec une fonction jouable qui te retourne aussi un bool
    - victoire : Vide=pas de gagnant, Rond=joueur Rond gagne, Croix=joueur croix gagne
    - jouable : true si on eput encore jouer, false si la partie est terminée
    Pensez à consulter la FAQ ou les cours et tutoriels de la section C++.
    Un peu de programmation réseau ?
    Aucune aide via MP ne sera dispensée. Merci d'utiliser les forums prévus à cet effet.

  18. #18
    Membre expérimenté
    Homme Profil pro
    Inscrit en
    Décembre 2010
    Messages
    734
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Décembre 2010
    Messages : 734
    Points : 1 475
    Points
    1 475
    Par défaut
    Citation Envoyé par koala01 Voir le message
    Heuu... Tu ne viendrais pas du monde de java, quelques fois
    Même en java, les superclasses qui servent à rien...ne servent à rien

  19. #19
    Membre régulier Avatar de Schaublore
    Homme Profil pro
    Manuel
    Inscrit en
    Octobre 2014
    Messages
    61
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Manuel
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Octobre 2014
    Messages : 61
    Points : 93
    Points
    93
    Par défaut
    Etudiante_maths_info balance ton nouveau code qui corrige la grille (Un tableau bidimentionnel de 3x3 elements, ou un tableau linéaire de 9 element ) avec une fonction d'affichage propre. Promis on jéterai un oeil. Ton premiere code a trop de bug: la matrice est inversé, nom de fonction HorsSujet minimax(au lieu de min_max peut-etre) doublon de code: j'ai en mal aux cheveux.

    Bousk t'as donné une super piste pour structurer/modéliser ton code.


    PS: http://www-sop.inria.fr/oasis/person.../tp1/morpion.c
    Tromper son maitre, c'est se tromper soi meme.
    f(x) = y

  20. #20
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 30
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Finance

    Informations forums :
    Inscription : Octobre 2014
    Messages : 16
    Points : 0
    Points
    0
    Par défaut
    Je vous mets ça sur le forum ce soir... Par contre je n'ai pas vraiment changé ma fonction d'affichage, je ne vois pas en quoi elle n'est pas "propre"... Et on me parle de matrice, mais où a-t-on une matrice ?! Et pour les noms de fonctions, oui je parlais de min_max, et les autres ont des noms adaptés je trouve, en tout cas ça reflète ce que je voulais qu'elles fassent Et encore pour le doublon c'est dans la fonction minimax c'est ça ? Si oui j'attendais de voir où est le bug pour la factoriser... Apparemment ça n'est pas la meilleure solution, donc je vais sûrement changer ça également Après ces changements je vous transmettrai mon nouveau code, en espérant qu'il soit moins désagréable pour vous Et pour ce qui concerne de faire du cas par cas, le prof n'en veut pas, il veut qu'on utilise la théorie du min-max (je lui en ai parlé ce matin)... Dommage ! Sinon, je ne doute pas que Bousk me donne de bonnes indications mais je n'ai jamais utilisé struct et enum, je ne sais même pas ce que c'est...

    PS : j'ai déjà codé un morpion qui fait jouer deux joueurs, et mon prof est "d'accord" avec mon programme..

Discussions similaires

  1. Probleme morpion avec SDL
    Par str0ofiy dans le forum C
    Réponses: 1
    Dernier message: 18/07/2011, 20h21
  2. programmer un morpion avec python
    Par titimaxou dans le forum Général Python
    Réponses: 33
    Dernier message: 19/03/2009, 13h26
  3. IA d'un morpion avec MiniMax
    Par georges_jung dans le forum Intelligence artificielle
    Réponses: 4
    Dernier message: 05/06/2007, 10h48
  4. Peut-on programmer un morpion avec Prolog ?
    Par c_khadi dans le forum Prolog
    Réponses: 1
    Dernier message: 16/12/2006, 21h37
  5. [Débutant] Jeu Morpion en C++ avec OpenGL
    Par Paulinho dans le forum OpenGL
    Réponses: 2
    Dernier message: 31/03/2006, 13h15

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo