Help with 2048 game

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 <string
Last edited on
Now left_push works great I tested it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#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){
        return false;
    }

    // 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){
            return false;
        }
    return true;
}


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?

Topic archived. No new replies allowed.