123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
#include <iostream> #include <conio.h> #include <vector> #include <cstdlib> #include <time.h> #include <windows.h> #include <algorithm> using namespace std; void board(int numbers[16]){ system("cls"); for(int i = 0; i < 16; i++){ if(numbers[i]==0)cout << " "; else cout << numbers[i]; if(i == 3 || i == 7 || i == 11 || i == 15) cout << endl; } } void genrnd(int numbers[16]){ vector<int> rndlist; for(int i = 0; i < 16; i++){ if(numbers[i]==0){ rndlist.push_back(i); } } int randindex, two_four; random_shuffle ( rndlist.begin(), rndlist.end() ); srand (time(NULL)); randindex = rand() % rndlist.size(); two_four = rand() % 2; if(two_four>0)two_four=4; else two_four = 2; numbers[rndlist[randindex]]=two_four; } void align(int numbers[16], int id) { int d = 0; if(id == 1){ for(int i = 0; i < 4; i++){ for(int k = i+12; k > i; k-=4){ if(numbers[k-4]==0){ numbers[k-4]=numbers[k]; numbers[k]=0; } else if(numbers[k-4]==numbers[k]){ numbers[k-4]+=numbers[k]; numbers[k]=0; //k-=4; } } } } if(id == 2){ for(int k = 16; k > 0; k-=4){ for(int i = k-1; i > k-4; i--){ if(numbers[i-1]==0){ numbers[i-1]=numbers[i]; numbers[i]=0; } else if(numbers[i-1]==numbers[i]){ numbers[i-1]+=numbers[i]; numbers[i]=0; //i-=1; } } } } if(id == 3){ for(int i = 0; i < 4; i++){ for(int k = i; k <= i+8; k+=4){ if(numbers[k+4]==0){ numbers[k+4]=numbers[k]; numbers[k]=0; } else if(numbers[k+4]==numbers[k]){ numbers[k+4]+=numbers[k]; numbers[k]=0; //k+=4; } } } } if(id == 4){ for(int k = 0; k < 16; k+=4){ for(int i = k; i < k+3; i++){ if(numbers[i+1]==0){ numbers[i+1]=numbers[i]; numbers[i]=0; } else if(numbers[i+1]==numbers[i]){ numbers[i+1]+=numbers[i]; numbers[i]=0; //i+=1; } } } } genrnd(numbers); board(numbers); } int main(){ /// RANDOM START int numbers[16] = {0}; int randindex; srand (time(NULL)); for(int i = 0; i < 2; i++){ randindex = rand() % 16; if(numbers[randindex]==2)numbers[randindex]=4; else numbers[randindex] = 2; } /// RANDOM END board(numbers); bool lost = 0; int id = 0; while(!lost){ switch ( getch() ) { case 'w': align(numbers, 1); break; case 'a': align(numbers, 2); break; case 's': align(numbers, 3); break; case 'd': align(numbers, 4); break; default: board(numbers); cout << endl << endl << "Only WASD keys are recognized at the moment" << endl; break; } } }