For my 2048 game, I have made a function called left_push which pushes all the numbers in a grid to the left and adds two numbers if they are equal just like the original game. If a change has been made it returns true otherwise it returns false.
The issue is. In 2048 the numbers are in a grid and each row in the grid needs to be pushed to the left individually. Hence I introduces two limits ei and bi which allows us to only push a range of values to be able to left push each row individually.
Now left_push works great I tested it. However my left_push_all which is meant to change the range values to change which row we are pushing seems to be not working and when I run them both it just does not work.
I would appreciate any help. I have tried everything within my means and I cannot figure out what is wrong.
#include <iostream>
#include <iomanip>
#include <vector>
bool left_push(std::vector<int>& v, int bi, int ei);
int main()
{
std::vector<int> v { 1, 0, 1,
0, 1, 0,
1, 0, 1 } ;
std::cout << std::boolalpha << left_push(v, 3, 6) << '\n';
for(std::size_t i = 0; i < v.size(); ++i) {
std::cout << v[i] << ' ';
}
return 0;
}
bool left_push(std::vector<int>& v, int bi, int ei)
{
std::vector<int> tmp;
std::vector<int> tmp2;
int counter = 0;
// takes out the zeros
for(int i = bi; i < ei; ++i) {
if(v[i] != 0){
tmp.push_back(v[i]);
counter++;
}
}
// returns false if all equal to zero
if( counter == 0){
returnfalse;
}
// takes out values for later testing
for(std::size_t i = 0; i < v.size(); i++){
tmp2.push_back(v[i]);
}
// adds if equal
for(std::size_t i = 0; i < (tmp.size() - 1); i++){
if (tmp[i] == tmp[i+1] && tmp.size() != 0){
tmp[i] = tmp[i]+tmp[i];
tmp.erase( tmp.begin() + (i+1));
}
}
int x = 0;
//prints values back in
for(std::size_t i = bi; i< tmp.size(); i++){
v[i] = tmp[x];
x++;
}
// adds the zeros at the end
for(int i = x; i < ei; i++){
v[i] = 0;
}
//checks if there has been a change
if(v==tmp2){
returnfalse;
}
returntrue;
}
Output:
true
0 0 0 0 0 0 1 0 1
Is that the expected result? Shouldn't it be 1 0 1 1 0 0 1 0 1?