#include "snake.h" #include "utils.h" #include "drawBlock.h" #include "keys.h" #include "pos.h" #include int snake() { int tab[20][15]; int i,j; int score = 0; int size = 4; int loose = 0; int no_pop = 0; int applex = 0, appley = 0; int direction = RIGHT; volatile int k; Pos *Head = NULL; Pos *Bottom = NULL; Pos *Current = NULL; //On efface l'écran clearScreen(); //On initialise le tableau à zéro. for (i = 0; i < 20; i++) { for (j = 0; j < 15; j++) { tab[i][j] = 0; } } //On crée la chaine Bottom = malloc(sizeof(Pos*)); Bottom->x = 0; Bottom->y = 0; Current = Bottom; for (i = 0; i < size; i++) { draw16(Current->x,Current->y,0); tab[Current->x][Current->y] = 1; Current = Pos_add(Current,1,0); } draw16(Current->x,Current->y,0); tab[Current->x][Current->y] = 1; Head = Current; //On change la position de la pomme applex = abs((rand() % 19) + 1); appley = abs((rand() % 14) + 1); draw16(applex,appley,0); while (loose != 1 && !isKeyEscPressed()) { //Gestion des touches if (isKeyUpPressed()) { direction = UP; } else if (isKeyDownPressed()) { direction = DOWN; } else if (isKeyLeftPressed()) { direction = LEFT; } else if (isKeyRightPressed()) { direction = RIGHT; } //On gère le deplacement. switch (direction) { case LEFT: Head = Pos_add(Head,-1,0); break; case RIGHT: Head = Pos_add(Head,1,0); break; case UP: Head = Pos_add(Head,0,-1); break; case DOWN: Head = Pos_add(Head,0,1); break; } //On ajoute un element à la tête. if ( (Head->x > -1) && (Head->y > (-1))) { draw16(Head->x,Head->y,0); } //On verifie que la tête ne touche pas le corps if (tab[Head->x][Head->y] == 1) { loose = 1; } tab[Head->x][Head->y] = 1; //Si la tête touche une pomme. if ((applex == Head->x) && (appley == Head->y)) { score += 1; //On agrandit le serpent size++; no_pop = 1; //On change la position de la pomme do { applex = abs((rand() % 19) + 1); appley = abs((rand() % 14) + 1); } while (tab[applex][appley] == 1); draw16(applex,appley,0); } //On verifie que la tête est pas hors du terrain if ( (Head->x < 0) || (Head->x > 19) || (Head->y < 0) || (Head->y > 14) ) { loose = 1; } //On enlève le dernier element de la queue if (no_pop == 1) { no_pop = 0; } else { tab[Bottom->x][Bottom->y] = 0; draw16(Bottom->x,Bottom->y,15); Bottom = Pos_pop(Bottom); } //Hack pour faire mouliner le processeur for (k = 0; k < 1000000; k++) { i = k / 2; } } clearScreen(); return score; } int abs(int n) { if (n < 0) { return n * -1; } else { return n; } }