I have written a function for my 2048 game which takes in a certain range of values of a vector which represents an NxN grid where N is a square number and pushes them to the left just like the game. If any movement happens, it also returns a true statement.
For example:
The input range is such that LB is inclusive and UB is not. e.g bi <= x < ei
if the range was the whole vector ( bi = 0 to ei = 4)
v in : 1001
v out : 2000
Another example:
if the range if (bi = 0 and ei = 4)
v in : 101010101
v out: 200010101
Simple function it would seem:
Here is what I wrote for it:
bool left_push(std::vector<int>& v, int bi, int ei){
std::vector<int> tmp;
bool check = false;
for(int i= (bi) ; i< ei ; i++){
if(v[i]!= 0){
tmp.push_back(v[i]);
check = true;
}
}
for(int i = 0; i< tmp.size(); i++){
if( tmp[i]==tmp[i-1] && tmp[i]!=0 && i>0){
tmp[i-1] = tmp[i]+tmp[i];
tmp[i] = 0;
check = true;
}
}
int x = bi;
for( int i = 0; i < tmp.size(); i++ ){
if(tmp[i]!=0){
v[x] = tmp[i];
x++;
}
}
for( int i = x; i < ei ; i++ ){
v[i] = 0;
}
return check;
}
This function: prints non zero values into another vector to add them. Then adds adjacent numbers if they are equal and replaces empty index with zero. Then prints back non zero values back in to the original vector. And finally prints zeros in rest of indexes in range to complete what is needed.
Now this function works great. However in the 2048 game, you would need all the rows to be ''pushed'' individually. Hence I made a function which pushes each row to the left individually:
bool left_push_all(std::vector<int>&v){
int length = std::sqrt(v.size());
bool check = false;
for( int i = 0; i < length; i++){
int bi = i*length ;
int ei = (((i+1)*length)-1 );
left_push(v, bi, ei);
if(left_push(v, bi, ei)){
check = true;
}
}
return check;
}
The issue is when I do this, the input vector and the output vector are identical. Which means nothing is happening at all.
Is this a bug or have I just done something wrong?
Aucun commentaire:
Enregistrer un commentaire