Gestion du deplacement du serpent: snake

SDL c

Le problème exposé dans ce sujet a été résolu.

Bonjour a tous j’ai un problème au niveau de la gestion de mon snake (son déplacement); Le serpent en grandissant insère les élements tjrs en diagonale ce qui selon moi n’est pas Normale: Ci dessous Le Code Complet: Merci de bien vouloir me suggérer une autre façon de voir le problème si nécessaire . J’accepte tout critique !

include <stdio.h>

include <stdbool.h>

include <stdlib.h>

include <time.h>

include <SDL2/SDL.h>

include <SDL2/SDL_ttf.h>

include <SDL2/SDL_image.h>

include <SDL2/SDL_mixer.h>

define WIN_WIDTH 800

define WIN_HEIGHT 700

define N_MAX 100

define SPEED 4

enum {UP,DOWN,LEFT,RIGHT}; typedef struct { SDL_bool key[SDL_NUM_SCANCODES]; SDL_bool quit; int mousex,mousey; int mousexrel,mouseyrel; int xwheel,ywheel; SDL_bool mouse[6]; }Input;

typedef struct { SDL_Texture *image; SDL_Rect pos[N_MAX]; int direction; int taille; }Serpent;

typedef struct { SDL_Texture *image; SDL_Rect pos; }Pomme;

int init_SDL(SDL_Window window,SDL_Renderer renderer); int setWindowColor(SDL_Renderer renderer,SDL_Color color); void updateEvents(Input in); SDL_Texture loadImage(SDL_Renderer renderer,char path); int nbreAleatoire(int max,int min); int collision(SDL_Rect pos1,SDL_Rect pos2); int game_play(Input in,Serpent serpent,Pomme pomme); int affichage(Serpent serpent,Pomme pomme,SDL_Renderer *renderer);

int init_SDL(SDL_Window window,SDL_Renderer renderer) { SDL_Surface *icone = NULL; if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)) { fprintf(stderr, " Erreur SDL_Init() %s\n",SDL_GetError()); return -1; } if(!IMG_Init(IMG_INIT_JPG)) { fprintf(stderr, " Erreur IMG_Init() %s\n",IMG_GetError()); return -1; } if(Mix_OpenAudio(44100,MIX_DEFAULT_FORMAT,2,2048)) { fprintf(stderr, " Erreur Mix_OpenAudio() %s\n",Mix_GetError() ); return -1; }

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
 *window = SDL_CreateWindow("Test",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,WIN_WIDTH,WIN_HEIGHT,SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL);
 if(!*window)
 {
    fprintf(stderr, " SDL_CreateWindow() %s\n",SDL_GetError() );
    return -1;
 }
 *renderer = SDL_CreateRenderer(*window,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
 if(!*renderer)
 {
    fprintf(stderr, " SDL_CreateRenderer() %s\n",SDL_GetError() );
    return -1;
 }

icone = IMG_Load("sdl_icone.bmp"); if(!icone) { fprintf(stderr, " Erreur IMG_Load() %s\n",IMG_GetError() ); return -1; } SDL_SetWindowIcon(window,icone); SDL_FreeSurface(icone); icone = NULL; return 0; } int collision(SDL_Rect pos1,SDL_Rect pos2) { if(pos1.x + pos1.w <= pos2.x pos1.x>= pos2.x + pos2.w) return 0; if(pos1.y + pos1.h <= pos2.y pos1.y >= pos2.y + pos2.h) return 0; return 1; } int nbreAleatoire(int max,int min) { static int initialized=0; if(!initialized) { initialized = 1; srand(time(NULL)); } return rand()%(max - min)+min; } int setWindowColor(SDL_Renderer renderer,SDL_Color color) { if(SDL_SetRenderDrawColor(renderer,color.r,color.g,color.b,color.a)) { fprintf(stderr, "%s\n", SDL_GetError()); return -1; } if(SDL_RenderClear(renderer)) { fprintf(stderr, "%s\n",SDL_GetError() ); return -1; } return 0; } int init_Game(Serpent serpent,Pomme pomme,SDL_Renderer *renderer) {

serpent->image = loadImage(renderer,"rouge.bmp"); if(SDL_QueryTexture(serpent->image,NULL,NULL,&serpent->pos[0].w,&serpent->pos[0].h)) { fprintf(stderr, " Erreur SDL_QueryTexture() %s\n", SDL_GetError()); return -1; } serpent->pos[0].x = nbreAleatoire(800,0); serpent->pos[0].y = nbreAleatoire(700,0); serpent->direction = UP; serpent->taille = 1; pomme->image = loadImage(renderer,"bleu.bmp"); if(SDL_QueryTexture(pomme->image,NULL,NULL,&pomme->pos.w,&pomme->pos.h)) { fprintf(stderr, " Erreur SDL_QueryTexture() %s\n", SDL_GetError()); return -1; } do{ pomme->pos.x = nbreAleatoire(800,0); pomme->pos.y = nbreAleatoire(700,0); }while(collision(serpent->pos[0],pomme->pos));

return 0; }

int game_play(Input in,Serpent serpent,Pomme *pomme) {

if(in->key[SDL_SCANCODE_UP]) { serpent->direction = UP; } if(in->key[SDL_SCANCODE_DOWN]) { serpent->direction = DOWN; } if(in->key[SDL_SCANCODE_RIGHT]) { serpent->direction = RIGHT; } if(in->key[SDL_SCANCODE_LEFT]) { serpent->direction = LEFT; } switch(serpent->direction) { case UP: { serpent->pos[0].y -=SPEED; } break; case DOWN: { serpent->pos[0].y +=SPEED; } break; case RIGHT: { serpent->pos[0].x +=SPEED; } break; case LEFT: { serpent->pos[0].x -=SPEED; } break; default: break; } if(collision(serpent->pos[0],pomme->pos)){ pomme->pos.x = nbreAleatoire(800,0); pomme->pos.y = nbreAleatoire(700,0); serpent->taille++; };

return 0; }

int affichage(Serpent serpent,Pomme pomme,SDL_Renderer *renderer) { if(SDL_RenderClear(renderer)) { fprintf(stderr, " Erreur SDL_RenderClear() %s\n",SDL_GetError() ); return -1; }

for (int i = 0; i <=serpent->taille; ++i) { if(i>0) { serpent->pos[i].x = serpent->pos[i-1].x; serpent->pos[i].y = serpent->pos[i-1].y; serpent->pos[i].w = serpent->pos[i-1].w; serpent->pos[i].h = serpent->pos[i-1].h; } if(SDL_RenderCopy(renderer,serpent->image,NULL,&serpent->pos[i])) { fprintf(stderr, " Erreur SDL_RenderCopy() %s\n", SDL_GetError()); return -1; }

if(SDL_RenderCopy(renderer,pomme->image,NULL,&pomme->pos)) { fprintf(stderr, "Erreur SDL_RenderCopy() %s\n", SDL_GetError()); return -1; } }

return 0; }

void updateEvents(Input *in) { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: in->quit = SDL_TRUE; break; case SDL_KEYDOWN: in->key[event.key.keysym.scancode] = SDL_TRUE; break; case SDL_KEYUP: in->key[event.key.keysym.scancode] = SDL_FALSE; break; case SDL_MOUSEMOTION: { in->mousex = event.motion.x; in->mousey = event.motion.y; in->mousexrel = event.motion.xrel; in->mouseyrel = event.motion.yrel; } break; case SDL_MOUSEWHEEL: { in->xwheel = event.wheel.x; in->ywheel = event.wheel.y;
} break; case SDL_MOUSEBUTTONDOWN: in->mouse[event.button.button] = SDL_TRUE; break; case SDL_MOUSEBUTTONUP: in->mouse[event.button.button] = SDL_FALSE; break; default: break;

1
2
    }
}

} SDL_Texture loadImage(SDL_Renderer renderer,char path) { SDL_Texture textureL = NULL; SDL_Surface *image = IMG_Load(path); if(!image) { fprintf(stderr, " Erreur IMG_Load() %s\n",IMG_GetError() ); return NULL; } if(SDL_SetColorKey(image,SDL_TRUE,SDL_MapRGB(image->format,255,255,255))) { fprintf(stderr, " Erreur SDL_SetColorKey() %s\n",SDL_GetError()); exit (EXIT_FAILURE); } textureL = SDL_CreateTextureFromSurface(renderer,image); if(!textureL) { fprintf(stderr, " Erreur SDL_CreateTextureFromSurface()%s\n",SDL_GetError()); exit(EXIT_FAILURE); } SDL_FreeSurface(image); image = NULL; return textureL; }

int main(int argc, char *argv[]) {

SDL_Window window = NULL; SDL_Renderer renderer = NULL; //SDL_Color color = {0,255,0};

Input in; Serpent serpent; Pomme pomme;

int statut = EXIT_FAILURE;

if(init_SDL(&window,&renderer)) goto Quit; memset(&in,SDL_FALSE,sizeof(Input)); if(init_Game(&serpent,&pomme,renderer)) goto Quit;

while(!in.quit) { updateEvents(&in);

if(game_play(&in,&serpent,&pomme)) goto Quit; if(affichage(&serpent,&pomme,renderer)) goto Quit;

SDL_RenderPresent(renderer); }

statut = EXIT_SUCCESS; Quit: if(renderer) SDL_DestroyRenderer(renderer); if(window) SDL_DestroyWindow(window); Mix_CloseAudio(); IMG_Quit(); SDL_Quit(); return statut;

}

Ok Compris

  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
 #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>

#define WIN_WIDTH 800
#define WIN_HEIGHT 700
#define N_MAX 100
#define SPEED 4

enum {UP,DOWN,LEFT,RIGHT};
typedef struct 
{
    SDL_bool key[SDL_NUM_SCANCODES];
    SDL_bool quit;
    int mousex,mousey;
    int mousexrel,mouseyrel;
    int xwheel,ywheel;
    SDL_bool mouse[6];
}Input;

typedef struct 
{
  SDL_Texture *image;
  SDL_Rect pos[N_MAX];
  int direction;
  int taille;
}Serpent;

typedef struct 
{
  SDL_Texture *image;
  SDL_Rect pos;
}Pomme;

int init_SDL(SDL_Window **window,SDL_Renderer **renderer);
int setWindowColor(SDL_Renderer *renderer,SDL_Color color);
void updateEvents(Input *in);
SDL_Texture *loadImage(SDL_Renderer *renderer,char *path);
int nbreAleatoire(int max,int min);
int collision(SDL_Rect pos1,SDL_Rect pos2);
int game_play(Input *in,Serpent *serpent,Pomme *pomme);
int affichage(Serpent *serpent,Pomme *pomme,SDL_Renderer *renderer);

int init_SDL(SDL_Window **window,SDL_Renderer **renderer)
{
  SDL_Surface *icone = NULL;
     if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO))
     {
     fprintf(stderr, " Erreur SDL_Init() %s\n",SDL_GetError());
      return -1;
     }
     if(!IMG_Init(IMG_INIT_JPG))
     {
        fprintf(stderr, " Erreur IMG_Init() %s\n",IMG_GetError());
        return -1;
     }
     if(Mix_OpenAudio(44100,MIX_DEFAULT_FORMAT,2,2048))
     {
     fprintf(stderr, " Erreur Mix_OpenAudio() %s\n",Mix_GetError() );
     return -1;
     }

     *window = SDL_CreateWindow("Test",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,WIN_WIDTH,WIN_HEIGHT,SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL);
     if(!*window)
     {
        fprintf(stderr, " SDL_CreateWindow() %s\n",SDL_GetError() );
        return -1;
     }
     *renderer = SDL_CreateRenderer(*window,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
     if(!*renderer)
     {
        fprintf(stderr, " SDL_CreateRenderer() %s\n",SDL_GetError() );
        return -1;
     }
   icone = IMG_Load("sdl_icone.bmp");
   if(!icone)
   {
    fprintf(stderr, " Erreur IMG_Load() %s\n",IMG_GetError() );
    return -1;
   }
  SDL_SetWindowIcon(*window,icone);
  SDL_FreeSurface(icone);
  icone = NULL;
     return 0;
    }
  int collision(SDL_Rect pos1,SDL_Rect pos2)
  {
    if(pos1.x + pos1.w <= pos2.x || pos1.x>= pos2.x + pos2.w)
     return 0;
   if(pos1.y + pos1.h <= pos2.y || pos1.y >= pos2.y + pos2.h)
    return 0;
  return 1;
  }
int nbreAleatoire(int max,int min)
{
   static int initialized=0;
   if(!initialized)
   {
    initialized = 1;
    srand(time(NULL));
   }
   return rand()%(max - min)+min;
}
    int setWindowColor(SDL_Renderer *renderer,SDL_Color color)
    {
         if(SDL_SetRenderDrawColor(renderer,color.r,color.g,color.b,color.a))
         {
            fprintf(stderr, "%s\n", SDL_GetError());
            return -1;
         }
         if(SDL_RenderClear(renderer))
         {
            fprintf(stderr, "%s\n",SDL_GetError() );
            return -1;
         }
         return 0; 
   }
int init_Game(Serpent *serpent,Pomme *pomme,SDL_Renderer *renderer)
{

serpent->image = loadImage(renderer,"rouge.bmp");
if(SDL_QueryTexture(serpent->image,NULL,NULL,&serpent->pos[0].w,&serpent->pos[0].h))
{
  fprintf(stderr, " Erreur SDL_QueryTexture() %s\n", SDL_GetError());
  return -1;
}
serpent->pos[0].x = nbreAleatoire(800,0);
serpent->pos[0].y = nbreAleatoire(700,0);
serpent->direction = UP;
serpent->taille = 1;
pomme->image =  loadImage(renderer,"bleu.bmp");
if(SDL_QueryTexture(pomme->image,NULL,NULL,&pomme->pos.w,&pomme->pos.h))
{
  fprintf(stderr, " Erreur SDL_QueryTexture() %s\n", SDL_GetError());
  return -1;
}
do{
pomme->pos.x = nbreAleatoire(800,0);
pomme->pos.y = nbreAleatoire(700,0);
}while(collision(serpent->pos[0],pomme->pos));

return 0;
}

int game_play(Input *in,Serpent *serpent,Pomme *pomme)
{

if(in->key[SDL_SCANCODE_UP])
{
  serpent->direction = UP;
}
if(in->key[SDL_SCANCODE_DOWN])
{
  serpent->direction = DOWN;
}
if(in->key[SDL_SCANCODE_RIGHT])
{
  serpent->direction = RIGHT;
}
if(in->key[SDL_SCANCODE_LEFT])
{
  serpent->direction = LEFT;
}
switch(serpent->direction)
{
  case UP:
  {
    serpent->pos[0].y -=SPEED;
  }
  break;
  case DOWN:
  {
    serpent->pos[0].y +=SPEED;
  }
  break;
  case RIGHT:
  {
    serpent->pos[0].x +=SPEED;
  }
  break;
  case LEFT:
  {
    serpent->pos[0].x -=SPEED;
  }
  break;
  default:
  break;
}
if(collision(serpent->pos[0],pomme->pos)){
pomme->pos.x = nbreAleatoire(800,0);
pomme->pos.y = nbreAleatoire(700,0);
serpent->taille++;
};

return 0;
}

int affichage(Serpent *serpent,Pomme *pomme,SDL_Renderer *renderer)
{
   if(SDL_RenderClear(renderer))
  {
    fprintf(stderr, " Erreur SDL_RenderClear() %s\n",SDL_GetError() );
    return -1;
  } 

  for (int i = 0; i <=serpent->taille; ++i)
  {
    if(i>0)
    {
       serpent->pos[i].x = serpent->pos[i-1].x;
          serpent->pos[i].y = serpent->pos[i-1].y;
      serpent->pos[i].w = serpent->pos[i-1].w;
      serpent->pos[i].h = serpent->pos[i-1].h; 
    }
     if(SDL_RenderCopy(renderer,serpent->image,NULL,&serpent->pos[i]))
  {
    fprintf(stderr, " Erreur SDL_RenderCopy() %s\n", SDL_GetError());
    return -1;
  }

  if(SDL_RenderCopy(renderer,pomme->image,NULL,&pomme->pos))
  {
    fprintf(stderr, "Erreur SDL_RenderCopy() %s\n", SDL_GetError());
    return -1;
  }
  }


  return 0;
}

void updateEvents(Input *in)
{
    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
        switch(event.type)
        {
            case SDL_QUIT: in->quit = SDL_TRUE;
            break;
            case SDL_KEYDOWN:
             in->key[event.key.keysym.scancode] = SDL_TRUE;
             break;
             case SDL_KEYUP:
             in->key[event.key.keysym.scancode] = SDL_FALSE;
             break;
             case SDL_MOUSEMOTION:
             {
                in->mousex = event.motion.x;
             in->mousey = event.motion.y;
             in->mousexrel = event.motion.xrel;
             in->mouseyrel = event.motion.yrel;
             }
             break;
             case SDL_MOUSEWHEEL:
             {
             in->xwheel = event.wheel.x;
             in->ywheel = event.wheel.y;    
             }
             break;
             case SDL_MOUSEBUTTONDOWN:
             in->mouse[event.button.button] = SDL_TRUE;
             break;
             case SDL_MOUSEBUTTONUP:
             in->mouse[event.button.button] = SDL_FALSE;
             break;
             default:
             break;

        }
    }
}
   SDL_Texture *loadImage(SDL_Renderer *renderer,char *path)
  {
    SDL_Texture* textureL = NULL;
    SDL_Surface *image = IMG_Load(path);
    if(!image)
    {
        fprintf(stderr, " Erreur IMG_Load() %s\n",IMG_GetError() );
        return NULL;
    }
    if(SDL_SetColorKey(image,SDL_TRUE,SDL_MapRGB(image->format,255,255,255)))
        {
            fprintf(stderr, " Erreur SDL_SetColorKey() %s\n",SDL_GetError());
            exit (EXIT_FAILURE);
        }
        textureL = SDL_CreateTextureFromSurface(renderer,image);
      if(!textureL)
      {
        fprintf(stderr, " Erreur SDL_CreateTextureFromSurface()%s\n",SDL_GetError());
        exit(EXIT_FAILURE);
      }
      SDL_FreeSurface(image);
      image = NULL;
    return textureL;
  }



int main(int argc, char *argv[])
{


   SDL_Window *window = NULL;
   SDL_Renderer *renderer = NULL;
   //SDL_Color color = {0,255,0};

   Input in;
   Serpent serpent;
   Pomme pomme;

   int statut = EXIT_FAILURE;

   if(init_SDL(&window,&renderer)) goto Quit;
  memset(&in,SDL_FALSE,sizeof(Input));
    if(init_Game(&serpent,&pomme,renderer)) goto Quit;

   while(!in.quit)
   {
   updateEvents(&in);

 if(game_play(&in,&serpent,&pomme)) goto Quit;
 if(affichage(&serpent,&pomme,renderer)) goto Quit;

   SDL_RenderPresent(renderer);
   }

 statut = EXIT_SUCCESS;
   Quit:
   if(renderer) SDL_DestroyRenderer(renderer);
   if(window) SDL_DestroyWindow(window);
   Mix_CloseAudio();
   IMG_Quit();
   SDL_Quit();
    return statut;

}

@victor et @Raphaelx : moi j’aurais dis plus comme ceci ;)

1
2
3
  ```c

  ```

@Raphaelx :

Le serpent en grandissant insère les élements tjrs en diagonale ce qui selon moi n’est pas Normale

J’ai pas tout compris là ,je crois qu’il va falloir que tu expliques un peu plus.

+0 -0

Ok Le Serpent En Inserant les Element Les Inserent de facon diagonale (premierere diagonale d’une matrice)

un peu comme ceci:

* * le premier * est la tete … NB Avec Le Code Ci dessous Il N’ajoute rien(il ne grandit pas ) (C’en Faisant ceci serpentpos[i].x = 20 + serpantpos[i-1].x serpentpos[i].y = 20 + serpantpos[i-1].y Qu’il fait ca diagonale): Merci .

Salut.

Je comprends pas tout (entre problème de formatage des messages et le gros pavé de code…), mais par contre si je résume ton code du message ci dessus, tu fais en gros :

$$ x_{t+1} = x_t + 20\\ y_{t+1} = y_t + 20 $$

donc oui, c’est normal que ca ajoute en diagonale.

Soit :

  • tu agrandis le serpent dans le prolongement de la queue (et c’est potentiellement complexe quand il tournicote dans tout les sens pour savoir la direction finale de la queue…)
  • tu rajoute une case au serpent "juste après la tête", i.e. à l’endroit où il vient de manger le bonbec.

my 2cents.

Connectez-vous pour pouvoir poster un message.
Connexion

Pas encore membre ?

Créez un compte en une minute pour profiter pleinement de toutes les fonctionnalités de Zeste de Savoir. Ici, tout est gratuit et sans publicité.
Créer un compte