Pas de dépendances
#ifdef WIN32 #include <windows.h> #include <conio.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define WIDTH 4 void LocateColor(int x,int y,int color) { #ifdef WIN32 COORD C; HANDLE H=GetStdHandle(STD_OUTPUT_HANDLE); C.X=(SHORT)x; C.Y=(SHORT)y; SetConsoleTextAttribute(H,(WORD)color); SetConsoleCursorPosition(H,C); #endif } typedef struct Jeu { int Tab[WIDTH*WIDTH]; } Jeu; int Index(int d,int x,int y) { switch (d) { case 0: // droite return y*WIDTH+x; case 1: // gauche return y*WIDTH+(WIDTH-x-1); case 2: // bas return x*WIDTH+y; case 3: // haut return (WIDTH-x-1)*WIDTH+y; default: break; } return 0; } int Log2(int i) { int res = 0; while(!((i>>res)&1)) res++; return res; } void Show(Jeu* J) { int i,j; for(j=0;j<WIDTH;j++) { for(i=0;i<WIDTH;i++) { int val = J->Tab[Index(0,i,j)]; LocateColor(6*i,j,15); // blanc pour les | if (val==0) printf(" |"); else { LocateColor(6*i,j,(Log2(val)+1)|8); // FOREGROUNDINTENSITY printf("%4d |",val); } } printf("\n"); } printf("\n"); } void NewCase(Jeu* J) { int choix = 0; do { choix = rand()%(WIDTH*WIDTH); } while (J->Tab[choix]!=0); J->Tab[choix] = 1; } int Pousse_Fusion(Jeu* J,int dir,int y,int fusion,int verif) { int i; for(i=1;i<WIDTH;i++) { int crt = J->Tab[Index(dir,i,y)]; int pred = J->Tab[Index(dir,i-1,y)]; if ((fusion==0 && pred==0 && crt>0) || (fusion==1 && pred==crt && crt!=0)) { if (verif) return 1; J->Tab[Index(dir,i-1,y)] = crt+pred; J->Tab[Index(dir,i,y)] = 0; if (fusion==0) i=0; // recommence. } } return 0; } int Move(Jeu* J,int dir) { int i; for(i=0;i<WIDTH;i++) { Pousse_Fusion(J,dir,i,0,0); Pousse_Fusion(J,dir,i,1,0); Pousse_Fusion(J,dir,i,0,0); } return 0; } int Possible(Jeu* J,int dir) { int i; for(i=0;i<WIDTH;i++) if (Pousse_Fusion(J,dir,i,0,1) || Pousse_Fusion(J,dir,i,1,1)) return 1; return 0; } int GetDir() { char* dir = "fhtg"; // keyboard int key,res,i; do { #ifdef WIN32 key = getch(); #else key = getchar(); #endif res = -1; for(i=0;i<4;i++) if (key == dir[i]) res = i; } while(res==-1); return res; } int main() { Jeu J; srand((unsigned int)time(NULL)); memset(&J,0,sizeof(Jeu)); NewCase(&J); NewCase(&J); while(Possible(&J,0) || Possible(&J,1) || Possible(&J,2) || Possible(&J,3)) { int dir; Show(&J); do { dir = GetDir(); } while (!Possible(&J,dir)); Move(&J,dir); NewCase(&J); } return 0; }
Use keys FGHT